2 * Base library for MediaWiki.
4 * Exposed as globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
11 var mw
= ( function ( $, undefined ) {
16 var hasOwn
= Object
.prototype.hasOwnProperty
,
17 slice
= Array
.prototype.slice
,
18 trackCallbacks
= $.Callbacks( 'memory' ),
22 * Log a message to window.console, if possible. Useful to force logging of some
23 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
24 * Gets console references in each invocation, so that delayed debugging tools work
25 * fine. No need for optimization here, which would only result in losing logs.
29 * @param {string} msg text for the log entry.
32 function log( msg
, e
) {
33 var console
= window
.console
;
34 if ( console
&& console
.log
) {
36 // If we have an exception object, log it through .error() to trigger
37 // proper stacktraces in browsers that support it. There are no (known)
38 // browsers that don't support .error(), that do support .log() and
39 // have useful exception handling through .log().
40 if ( e
&& console
.error
) {
41 console
.error( String( e
), e
);
46 /* Object constructors */
49 * Creates an object that can be read from or written to from prototype functions
50 * that allow both single and multiple variables at once.
54 * var addies, wanted, results;
56 * // Create your address book
57 * addies = new mw.Map();
59 * // This data could be coming from an external source (eg. API/AJAX)
61 * 'John Doe' : '10 Wall Street, New York, USA',
62 * 'Jane Jackson' : '21 Oxford St, London, UK',
63 * 'Dominique van Halen' : 'Kalverstraat 7, Amsterdam, NL'
66 * wanted = ['Dominique van Halen', 'George Johnson', 'Jane Jackson'];
68 * // You can detect missing keys first
69 * if ( !addies.exists( wanted ) ) {
70 * // One or more are missing (in this case: "George Johnson")
71 * mw.log( 'One or more names were not found in your address book' );
74 * // Or just let it give you what it can
75 * results = addies.get( wanted, 'Middle of Nowhere, Alaska, US' );
76 * mw.log( results['Jane Jackson'] ); // "21 Oxford St, London, UK"
77 * mw.log( results['George Johnson'] ); // "Middle of Nowhere, Alaska, US"
82 * @param {Object|boolean} [values] Value-bearing object to map, or boolean
83 * true to map over the global object. Defaults to an empty object.
85 function Map( values
) {
86 this.values
= values
=== true ? window
: ( values
|| {} );
92 * Get the value of one or multiple a keys.
94 * If called with no arguments, all values will be returned.
96 * @param {string|Array} selection String key or array of keys to get values for.
97 * @param {Mixed} [fallback] Value to use in case key(s) do not exist.
98 * @return mixed If selection was a string returns the value or null,
99 * If selection was an array, returns an object of key/values (value is null if not found),
100 * If selection was not passed or invalid, will return the 'values' object member (be careful as
101 * objects are always passed by reference in JavaScript!).
102 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
104 get: function ( selection
, fallback
) {
106 // If we only do this in the `return` block, it'll fail for the
107 // call to get() from the mutli-selection block.
108 fallback
= arguments
.length
> 1 ? fallback
: null;
110 if ( $.isArray( selection
) ) {
111 selection
= slice
.call( selection
);
113 for ( i
= 0; i
< selection
.length
; i
++ ) {
114 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
119 if ( typeof selection
=== 'string' ) {
120 if ( !hasOwn
.call( this.values
, selection
) ) {
123 return this.values
[selection
];
126 if ( selection
=== undefined ) {
130 // invalid selection key
135 * Sets one or multiple key/value pairs.
137 * @param {string|Object} selection String key to set value for, or object mapping keys to values.
138 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
139 * @return {Boolean} This returns true on success, false on failure.
141 set: function ( selection
, value
) {
144 if ( $.isPlainObject( selection
) ) {
145 for ( s
in selection
) {
146 this.values
[s
] = selection
[s
];
150 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
151 this.values
[selection
] = value
;
158 * Checks if one or multiple keys exist.
160 * @param {Mixed} selection String key or array of keys to check
161 * @return {boolean} Existence of key(s)
163 exists: function ( selection
) {
166 if ( $.isArray( selection
) ) {
167 for ( s
= 0; s
< selection
.length
; s
++ ) {
168 if ( typeof selection
[s
] !== 'string' || !hasOwn
.call( this.values
, selection
[s
] ) ) {
174 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
179 * Object constructor for messages.
181 * Similar to the Message class in MediaWiki PHP.
183 * Format defaults to 'text'.
189 * 'hello': 'Hello world',
190 * 'hello-user': 'Hello, $1!',
191 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
194 * obj = new mw.Message( mw.messages, 'hello' );
195 * mw.log( obj.text() );
198 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
199 * mw.log( obj.text() );
200 * // Hello, John Doe!
202 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
203 * mw.log( obj.text() );
204 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
206 * // Using mw.message shortcut
207 * obj = mw.message( 'hello-user', 'John Doe' );
208 * mw.log( obj.text() );
209 * // Hello, John Doe!
211 * // Using mw.msg shortcut
212 * str = mw.msg( 'hello-user', 'John Doe' );
214 * // Hello, John Doe!
216 * // Different formats
217 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
219 * obj.format = 'text';
220 * str = obj.toString();
225 * // Hello, John "Wiki" <3 Doe!
227 * mw.log( obj.escaped() );
228 * // Hello, John "Wiki" <3 Doe!
233 * @param {mw.Map} map Message storage
234 * @param {string} key
235 * @param {Array} [parameters]
237 function Message( map
, key
, parameters
) {
238 this.format
= 'text';
241 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
245 Message
.prototype = {
247 * Simple message parser, does $N replacement and nothing else.
249 * This may be overridden to provide a more complex message parser.
251 * The primary override is in mediawiki.jqueryMsg.
253 * This function will not be called for nonexistent messages.
255 parser: function () {
256 var parameters
= this.parameters
;
257 return this.map
.get( this.key
).replace( /\$(\d+)/g, function ( str
, match
) {
258 var index
= parseInt( match
, 10 ) - 1;
259 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
264 * Appends (does not replace) parameters for replacement to the .parameters property.
266 * @param {Array} parameters
269 params: function ( parameters
) {
271 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
272 this.parameters
.push( parameters
[i
] );
278 * Converts message object to its string form based on the state of format.
280 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
282 toString: function () {
285 if ( !this.exists() ) {
286 // Use <key> as text if key does not exist
287 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
288 // format 'escaped' and 'parse' need to have the brackets and key html escaped
289 return mw
.html
.escape( '<' + this.key
+ '>' );
291 return '<' + this.key
+ '>';
294 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
295 text
= this.parser();
298 if ( this.format
=== 'escaped' ) {
299 text
= this.parser();
300 text
= mw
.html
.escape( text
);
307 * Changes format to 'parse' and converts message to string
309 * If jqueryMsg is loaded, this parses the message text from wikitext
310 * (where supported) to HTML
312 * Otherwise, it is equivalent to plain.
314 * @return {string} String form of parsed message
317 this.format
= 'parse';
318 return this.toString();
322 * Changes format to 'plain' and converts message to string
324 * This substitutes parameters, but otherwise does not change the
327 * @return {string} String form of plain message
330 this.format
= 'plain';
331 return this.toString();
335 * Changes format to 'text' and converts message to string
337 * If jqueryMsg is loaded, {{-transformation is done where supported
338 * (such as {{plural:}}, {{gender:}}, {{int:}}).
340 * Otherwise, it is equivalent to plain.
343 this.format
= 'text';
344 return this.toString();
348 * Changes the format to 'escaped' and converts message to string
350 * This is equivalent to using the 'text' format (see text method), then
351 * HTML-escaping the output.
353 * @return {string} String form of html escaped message
355 escaped: function () {
356 this.format
= 'escaped';
357 return this.toString();
361 * Checks if message exists
366 exists: function () {
367 return this.map
.exists( this.key
);
378 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
380 * On browsers that implement the Navigation Timing API, this function will produce floating-point
381 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
382 * it will fall back to using `Date`.
384 * @returns {number} Current time
387 var perf
= window
.performance
,
388 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
389 return navStart
&& typeof perf
.now
=== 'function' ?
390 function () { return navStart
+ perf
.now(); } :
391 function () { return +new Date(); };
395 * Track an analytic event.
397 * This method provides a generic means for MediaWiki JavaScript code to capture state
398 * information for analysis. Each logged event specifies a string topic name that describes
399 * the kind of event that it is. Topic names consist of dot-separated path components,
400 * arranged from most general to most specific. Each path component should have a clear and
401 * well-defined purpose.
403 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
404 * events that match their subcription, including those that fired before the handler was
407 * @param {string} topic Topic name
408 * @param {Object} [data] Data describing the event, encoded as an object
410 track: function ( topic
, data
) {
411 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
412 trackCallbacks
.fire( trackQueue
);
416 * Register a handler for subset of analytic events, specified by topic
418 * Handlers will be called once for each tracked event, including any events that fired before the
419 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
420 * the exact time at which the event fired, a string 'topic' property naming the event, and a
421 * 'data' property which is an object of event-specific data. The event topic and event data are
422 * also passed to the callback as the first and second arguments, respectively.
424 * @param {string} topic Handle events whose name starts with this string prefix
425 * @param {Function} callback Handler to call for each matching tracked event
427 trackSubscribe: function ( topic
, callback
) {
430 trackCallbacks
.add( function ( trackQueue
) {
432 for ( ; seen
< trackQueue
.length
; seen
++ ) {
433 event
= trackQueue
[ seen
];
434 if ( event
.topic
.indexOf( topic
) === 0 ) {
435 callback
.call( event
, event
.topic
, event
.data
);
441 // Make the Map constructor publicly available.
444 // Make the Message constructor publicly available.
448 * Map of configuration values
450 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
453 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
454 * global `window` object.
456 * @property {mw.Map} config
458 // Dummy placeholder. Re-assigned in ResourceLoaderStartupModule to an instance of `mw.Map`.
462 * Empty object that plugins can be installed in.
468 * Access container for deprecated functionality that can be moved from
469 * from their legacy location and attached to this object (e.g. a global
470 * function that is deprecated and as stop-gap can be exposed through here).
472 * This was reserved for future use but never ended up being used.
474 * @deprecated since 1.22: Let deprecated identifiers keep their original name
475 * and use mw.log#deprecate to create an access container for tracking.
481 * Localization system
489 * Get a message object.
491 * Shorcut for `new mw.Message( mw.messages, key, parameters )`.
494 * @param {string} key Key of message to get
495 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
496 * @return {mw.Message}
498 message: function ( key
) {
499 // Variadic arguments
500 var parameters
= slice
.call( arguments
, 1 );
501 return new Message( mw
.messages
, key
, parameters
);
505 * Get a message string using the (default) 'text' format.
507 * Shortcut for `mw.message( key, parameters... ).text()`.
510 * @param {string} key Key of message to get
511 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
515 return mw
.message
.apply( mw
.message
, arguments
).toString();
519 * Dummy placeholder for {@link mw.log}
523 // Also update the restoration of methods in mediawiki.log.js
524 // when adding or removing methods here.
525 var log = function () {};
533 * Write a message the console's warning channel.
534 * Also logs a stacktrace for easier debugging.
535 * Each action is silently ignored if the browser doesn't support it.
537 * @param {string...} msg Messages to output to console
539 log
.warn = function () {
540 var console
= window
.console
;
541 if ( console
&& console
.warn
) {
542 console
.warn
.apply( console
, arguments
);
543 if ( console
.trace
) {
550 * Create a property in a host object that, when accessed, will produce
551 * a deprecation warning in the console with backtrace.
553 * @param {Object} obj Host object of deprecated property
554 * @param {string} key Name of property to create in `obj`
555 * @param {Mixed} val The value this property should return when accessed
556 * @param {string} [msg] Optional text to include in the deprecation message.
558 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
560 } : function ( obj
, key
, val
, msg
) {
561 msg
= 'MWDeprecationWarning: Use of "' + key
+ '" property is deprecated.' +
562 ( msg
? ( ' ' + msg
) : '' );
564 Object
.defineProperty( obj
, key
, {
568 mw
.track( 'mw.deprecate', key
);
572 set: function ( newVal
) {
573 mw
.track( 'mw.deprecate', key
);
579 // IE8 can throw on Object.defineProperty
588 * Client-side module loader which integrates with the MediaWiki ResourceLoader
592 loader
: ( function () {
594 /* Private Members */
597 * Mapping of registered modules
599 * The jquery module is pre-registered, because it must have already
600 * been provided for this object to have been built, and in debug mode
601 * jquery would have been provided through a unique loader request,
602 * making it impossible to hold back registration of jquery until after
605 * For exact details on support for script, style and messages, look at
606 * mw.loader.implement.
611 * 'version': ############## (unix timestamp),
612 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
613 * 'group': 'somegroup', (or) null,
614 * 'source': 'local', 'someforeignwiki', (or) null
615 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error' or 'missing'
618 * 'messages': { 'key': 'value' },
627 // Mapping of sources, keyed by source-id, values are objects.
631 // 'loadScript': 'http://foo.bar/w/load.php'
636 // List of modules which will be loaded as when ready
638 // List of modules to be loaded
640 // List of callback functions waiting for modules to be ready to be called
642 // Selector cache for the marker element. Use getMarker() to get/use the marker!
644 // Buffer for addEmbeddedCSS.
646 // Callbacks for addEmbeddedCSS.
647 cssCallbacks
= $.Callbacks();
649 /* Private methods */
651 function getMarker() {
657 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
658 if ( $marker
.length
) {
661 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
662 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
668 * Create a new style tag and add it to the DOM.
671 * @param {string} text CSS text
672 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag should be
673 * inserted before. Otherwise it will be appended to `<head>`.
674 * @return {HTMLElement} Reference to the created `<style>` element.
676 function newStyleTag( text
, nextnode
) {
677 var s
= document
.createElement( 'style' );
678 // Insert into document before setting cssText (bug 33305)
680 // Must be inserted with native insertBefore, not $.fn.before.
681 // When using jQuery to insert it, like $nextnode.before( s ),
682 // then IE6 will throw "Access is denied" when trying to append
683 // to .cssText later. Some kind of weird security measure.
684 // http://stackoverflow.com/q/12586482/319266
685 // Works: jsfiddle.net/zJzMy/1
686 // Fails: jsfiddle.net/uJTQz
687 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
688 if ( nextnode
.jquery
) {
689 nextnode
= nextnode
.get( 0 );
691 nextnode
.parentNode
.insertBefore( s
, nextnode
);
693 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
695 if ( s
.styleSheet
) {
697 s
.styleSheet
.cssText
= text
;
700 // (Safari sometimes borks on non-string values,
701 // play safe by casting to a string, just in case.)
702 s
.appendChild( document
.createTextNode( String( text
) ) );
708 * Checks whether it is safe to add this css to a stylesheet.
711 * @param {string} cssText
712 * @return {boolean} False if a new one must be created.
714 function canExpandStylesheetWith( cssText
) {
715 // Makes sure that cssText containing `@import`
716 // rules will end up in a new stylesheet (as those only work when
717 // placed at the start of a stylesheet; bug 35562).
718 return cssText
.indexOf( '@import' ) === -1;
722 * Add a bit of CSS text to the current browser page.
724 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
725 * or create a new one based on whether the given `cssText` is safe for extension.
727 * @param {string} [cssText=cssBuffer] If called without cssText,
728 * the internal buffer will be inserted instead.
729 * @param {Function} [callback]
731 function addEmbeddedCSS( cssText
, callback
) {
735 cssCallbacks
.add( callback
);
738 // Yield once before inserting the <style> tag. There are likely
739 // more calls coming up which we can combine this way.
740 // Appending a stylesheet and waiting for the browser to repaint
741 // is fairly expensive, this reduces it (bug 45810)
743 // Be careful not to extend the buffer with css that needs a new stylesheet
744 if ( !cssBuffer
|| canExpandStylesheetWith( cssText
) ) {
745 // Linebreak for somewhat distinguishable sections
746 // (the rl-cachekey comment separating each)
747 cssBuffer
+= '\n' + cssText
;
748 // TODO: Use requestAnimationFrame in the future which will
749 // perform even better by not injecting styles while the browser
751 setTimeout( function () {
752 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
753 // (below version 13) has the non-standard behaviour of passing a
754 // numerical "lateness" value as first argument to this callback
755 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
761 // This is a delayed call and we got a buffer still
762 } else if ( cssBuffer
) {
766 // This is a delayed call, but buffer is already cleared by
767 // another delayed call.
771 // By default, always create a new <style>. Appending text
772 // to a <style> tag means the contents have to be re-parsed (bug 45810).
773 // Except, of course, in IE below 9, in there we default to
774 // re-using and appending to a <style> tag due to the
775 // IE stylesheet limit (bug 31676).
776 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
778 $style
= getMarker().prev();
779 // Verify that the the element before Marker actually is a
780 // <style> tag and one that came from ResourceLoader
781 // (not some other style tag or even a `<meta>` or `<script>`).
782 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
783 // There's already a dynamic <style> tag present and
784 // canExpandStylesheetWith() gave a green light to append more to it.
785 styleEl
= $style
.get( 0 );
786 if ( styleEl
.styleSheet
) {
788 styleEl
.styleSheet
.cssText
+= cssText
; // IE
790 log( 'addEmbeddedCSS fail', e
);
793 styleEl
.appendChild( document
.createTextNode( String( cssText
) ) );
795 cssCallbacks
.fire().empty();
800 $( newStyleTag( cssText
, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
802 cssCallbacks
.fire().empty();
806 * Generates an ISO8601 "basic" string from a UNIX timestamp
809 function formatVersionNumber( timestamp
) {
811 function pad( a
, b
, c
) {
812 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
814 d
.setTime( timestamp
* 1000 );
816 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
817 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
822 * Resolves dependencies and detects circular references.
825 * @param {string} module Name of the top-level module whose dependencies shall be
826 * resolved and sorted.
827 * @param {Array} resolved Returns a topological sort of the given module and its
828 * dependencies, such that later modules depend on earlier modules. The array
829 * contains the module names. If the array contains already some module names,
830 * this function appends its result to the pre-existing array.
831 * @param {Object} [unresolved] Hash used to track the current dependency
832 * chain; used to report loops in the dependency graph.
833 * @throws {Error} If any unregistered module or a dependency loop is encountered
835 function sortDependencies( module
, resolved
, unresolved
) {
838 if ( registry
[module
] === undefined ) {
839 throw new Error( 'Unknown dependency: ' + module
);
841 // Resolves dynamic loader function and replaces it with its own results
842 if ( $.isFunction( registry
[module
].dependencies
) ) {
843 registry
[module
].dependencies
= registry
[module
].dependencies();
844 // Ensures the module's dependencies are always in an array
845 if ( typeof registry
[module
].dependencies
!== 'object' ) {
846 registry
[module
].dependencies
= [registry
[module
].dependencies
];
849 if ( $.inArray( module
, resolved
) !== -1 ) {
850 // Module already resolved; nothing to do.
853 // unresolved is optional, supply it if not passed in
857 // Tracks down dependencies
858 deps
= registry
[module
].dependencies
;
860 for ( n
= 0; n
< len
; n
+= 1 ) {
861 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
862 if ( unresolved
[deps
[n
]] ) {
864 'Circular reference detected: ' + module
+
870 unresolved
[module
] = true;
871 sortDependencies( deps
[n
], resolved
, unresolved
);
872 delete unresolved
[module
];
875 resolved
[resolved
.length
] = module
;
879 * Gets a list of module names that a module depends on in their proper dependency
883 * @param {string} module Module name or array of string module names
884 * @return {Array} list of dependencies, including 'module'.
885 * @throws {Error} If circular reference is detected
887 function resolve( module
) {
890 // Allow calling with an array of module names
891 if ( $.isArray( module
) ) {
893 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
894 sortDependencies( module
[m
], resolved
);
899 if ( typeof module
=== 'string' ) {
901 sortDependencies( module
, resolved
);
905 throw new Error( 'Invalid module argument: ' + module
);
909 * Narrows a list of module names down to those matching a specific
910 * state (see comment on top of this scope for a list of valid states).
911 * One can also filter for 'unregistered', which will return the
912 * modules names that don't have a registry entry.
915 * @param {string|string[]} states Module states to filter by
916 * @param {Array} [modules] List of module names to filter (optional, by default the entire
918 * @return {Array} List of filtered module names
920 function filter( states
, modules
) {
921 var list
, module
, s
, m
;
923 // Allow states to be given as a string
924 if ( typeof states
=== 'string' ) {
927 // If called without a list of modules, build and use a list of all modules
929 if ( modules
=== undefined ) {
931 for ( module
in registry
) {
932 modules
[modules
.length
] = module
;
935 // Build a list of modules which are in one of the specified states
936 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
937 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
938 if ( registry
[modules
[m
]] === undefined ) {
939 // Module does not exist
940 if ( states
[s
] === 'unregistered' ) {
942 list
[list
.length
] = modules
[m
];
945 // Module exists, check state
946 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
948 list
[list
.length
] = modules
[m
];
957 * Determine whether all dependencies are in state 'ready', which means we may
958 * execute the module or job now.
961 * @param {Array} dependencies Dependencies (module names) to be checked.
962 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
964 function allReady( dependencies
) {
965 return filter( 'ready', dependencies
).length
=== dependencies
.length
;
969 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
970 * and modules that depend upon this module. if the given module failed, propagate the 'error'
971 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
972 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
975 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
977 function handlePending( module
) {
978 var j
, job
, hasErrors
, m
, stateChange
;
981 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) !== -1 ) {
982 // If the current module failed, mark all dependent modules also as failed.
983 // Iterate until steady-state to propagate the error state upwards in the
987 for ( m
in registry
) {
988 if ( $.inArray( registry
[m
].state
, ['error', 'missing'] ) === -1 ) {
989 if ( filter( ['error', 'missing'], registry
[m
].dependencies
).length
> 0 ) {
990 registry
[m
].state
= 'error';
995 } while ( stateChange
);
998 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
999 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
1000 hasErrors
= filter( ['error', 'missing'], jobs
[j
].dependencies
).length
> 0;
1001 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
1002 // All dependencies satisfied, or some have errors
1004 jobs
.splice( j
, 1 );
1008 if ( $.isFunction( job
.error
) ) {
1009 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [module
] );
1012 if ( $.isFunction( job
.ready
) ) {
1017 // A user-defined callback raised an exception.
1018 // Swallow it to protect our state machine!
1019 log( 'Exception thrown by job.error', e
);
1024 if ( registry
[module
].state
=== 'ready' ) {
1025 // The current module became 'ready'. Set it in the module store, and recursively execute all
1026 // dependent modules that are loaded and now have all dependencies satisfied.
1027 mw
.loader
.store
.set( module
, registry
[module
] );
1028 for ( m
in registry
) {
1029 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
1037 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
1038 * depending on whether document-ready has occurred yet and whether we are in async mode.
1041 * @param {string} src URL to script, will be used as the src attribute in the script tag
1042 * @param {Function} [callback] Callback which will be run when the script is done
1043 * @param {boolean} [async=false] Whether to load modules asynchronously.
1044 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1046 function addScript( src
, callback
, async
) {
1047 /*jshint evil:true */
1048 var script
, head
, done
;
1050 // Using isReady directly instead of storing it locally from
1051 // a $.fn.ready callback (bug 31895).
1052 if ( $.isReady
|| async
) {
1053 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
1054 // it uses XHR and eval for same-domain scripts, which we don't want because it
1055 // messes up line numbers.
1056 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
1058 // IE-safe way of getting the <head>. document.head isn't supported
1059 // in old IE, and doesn't work when in the <head>.
1061 head
= document
.getElementsByTagName( 'head' )[0] || document
.body
;
1063 script
= document
.createElement( 'script' );
1064 script
.async
= true;
1066 if ( $.isFunction( callback
) ) {
1067 script
.onload
= script
.onreadystatechange = function () {
1072 || /loaded|complete/.test( script
.readyState
)
1077 // Handle memory leak in IE
1078 script
.onload
= script
.onreadystatechange
= null;
1080 // Detach the element from the document
1081 if ( script
.parentNode
) {
1082 script
.parentNode
.removeChild( script
);
1085 // Dereference the element from javascript
1093 if ( window
.opera
) {
1094 // Appending to the <head> blocks rendering completely in Opera,
1095 // so append to the <body> after document ready. This means the
1096 // scripts only start loading after the document has been rendered,
1097 // but so be it. Opera users don't deserve faster web pages if their
1098 // browser makes it impossible.
1100 document
.body
.appendChild( script
);
1103 head
.appendChild( script
);
1106 document
.write( mw
.html
.element( 'script', { 'src': src
}, '' ) );
1107 if ( $.isFunction( callback
) ) {
1108 // Document.write is synchronous, so this is called when it's done
1109 // FIXME: that's a lie. doc.write isn't actually synchronous
1116 * Executes a loaded module, making it ready to use
1119 * @param {string} module Module name to execute
1121 function execute( module
) {
1122 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
,
1123 cssHandlesRegistered
= false;
1125 if ( registry
[module
] === undefined ) {
1126 throw new Error( 'Module has not been registered yet: ' + module
);
1127 } else if ( registry
[module
].state
=== 'registered' ) {
1128 throw new Error( 'Module has not been requested from the server yet: ' + module
);
1129 } else if ( registry
[module
].state
=== 'loading' ) {
1130 throw new Error( 'Module has not completed loading yet: ' + module
);
1131 } else if ( registry
[module
].state
=== 'ready' ) {
1132 throw new Error( 'Module has already been executed: ' + module
);
1136 * Define loop-function here for efficiency
1137 * and to avoid re-using badly scoped variables.
1140 function addLink( media
, url
) {
1141 var el
= document
.createElement( 'link' );
1142 getMarker().before( el
); // IE: Insert in dom before setting href
1143 el
.rel
= 'stylesheet';
1144 if ( media
&& media
!== 'all' ) {
1150 function runScript() {
1151 var script
, markModuleReady
, nestedAddScript
;
1153 script
= registry
[module
].script
;
1154 markModuleReady = function () {
1155 registry
[module
].state
= 'ready';
1156 handlePending( module
);
1158 nestedAddScript = function ( arr
, callback
, async
, i
) {
1159 // Recursively call addScript() in its own callback
1160 // for each element of arr.
1161 if ( i
>= arr
.length
) {
1162 // We're at the end of the array
1167 addScript( arr
[i
], function () {
1168 nestedAddScript( arr
, callback
, async
, i
+ 1 );
1172 if ( $.isArray( script
) ) {
1173 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
1174 } else if ( $.isFunction( script
) ) {
1175 registry
[module
].state
= 'ready';
1177 handlePending( module
);
1180 // This needs to NOT use mw.log because these errors are common in production mode
1181 // and not in debug mode, such as when a symbol that should be global isn't exported
1182 log( 'Exception thrown by ' + module
, e
);
1183 registry
[module
].state
= 'error';
1184 handlePending( module
);
1188 // This used to be inside runScript, but since that is now fired asychronously
1189 // (after CSS is loaded) we need to set it here right away. It is crucial that
1190 // when execute() is called this is set synchronously, otherwise modules will get
1191 // executed multiple times as the registry will state that it isn't loading yet.
1192 registry
[module
].state
= 'loading';
1194 // Add localizations to message system
1195 if ( $.isPlainObject( registry
[module
].messages
) ) {
1196 mw
.messages
.set( registry
[module
].messages
);
1199 if ( $.isReady
|| registry
[module
].async
) {
1200 // Make sure we don't run the scripts until all (potentially asynchronous)
1201 // stylesheet insertions have completed.
1204 checkCssHandles = function () {
1205 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1206 // one of the cssHandles is fired while we're still creating more handles.
1207 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1209 runScript
= undefined; // Revoke
1212 cssHandle = function () {
1213 var check
= checkCssHandles
;
1215 return function () {
1219 check
= undefined; // Revoke
1225 // We are in blocking mode, and so we can't afford to wait for CSS
1226 cssHandle = function () {};
1228 checkCssHandles
= runScript
;
1231 // Process styles (see also mw.loader.implement)
1232 // * back-compat: { <media>: css }
1233 // * back-compat: { <media>: [url, ..] }
1234 // * { "css": [css, ..] }
1235 // * { "url": { <media>: [url, ..] } }
1236 if ( $.isPlainObject( registry
[module
].style
) ) {
1237 for ( key
in registry
[module
].style
) {
1238 value
= registry
[module
].style
[key
];
1241 if ( key
!== 'url' && key
!== 'css' ) {
1242 // Backwards compatibility, key is a media-type
1243 if ( typeof value
=== 'string' ) {
1244 // back-compat: { <media>: css }
1245 // Ignore 'media' because it isn't supported (nor was it used).
1246 // Strings are pre-wrapped in "@media". The media-type was just ""
1247 // (because it had to be set to something).
1248 // This is one of the reasons why this format is no longer used.
1249 addEmbeddedCSS( value
, cssHandle() );
1251 // back-compat: { <media>: [url, ..] }
1257 // Array of css strings in key 'css',
1258 // or back-compat array of urls from media-type
1259 if ( $.isArray( value
) ) {
1260 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
1261 if ( key
=== 'bc-url' ) {
1262 // back-compat: { <media>: [url, ..] }
1263 addLink( media
, value
[i
] );
1264 } else if ( key
=== 'css' ) {
1265 // { "css": [css, ..] }
1266 addEmbeddedCSS( value
[i
], cssHandle() );
1269 // Not an array, but a regular object
1270 // Array of urls inside media-type key
1271 } else if ( typeof value
=== 'object' ) {
1272 // { "url": { <media>: [url, ..] } }
1273 for ( media
in value
) {
1274 urls
= value
[media
];
1275 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
1276 addLink( media
, urls
[i
] );
1284 cssHandlesRegistered
= true;
1289 * Adds a dependencies to the queue with optional callbacks to be run
1290 * when the dependencies are ready or fail
1293 * @param {string|string[]} dependencies Module name or array of string module names
1294 * @param {Function} [ready] Callback to execute when all dependencies are ready
1295 * @param {Function} [error] Callback to execute when any dependency fails
1296 * @param {boolean} [async=false] Whether to load modules asynchronously.
1297 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1299 function request( dependencies
, ready
, error
, async
) {
1302 // Allow calling by single module name
1303 if ( typeof dependencies
=== 'string' ) {
1304 dependencies
= [dependencies
];
1307 // Add ready and error callbacks if they were given
1308 if ( ready
!== undefined || error
!== undefined ) {
1309 jobs
[jobs
.length
] = {
1310 'dependencies': filter(
1311 ['registered', 'loading', 'loaded'],
1319 // Queue up any dependencies that are registered
1320 dependencies
= filter( ['registered'], dependencies
);
1321 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
1322 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
1323 queue
[queue
.length
] = dependencies
[n
];
1325 // Mark this module as async in the registry
1326 registry
[dependencies
[n
]].async
= true;
1335 function sortQuery( o
) {
1336 var sorted
= {}, key
, a
= [];
1338 if ( hasOwn
.call( o
, key
) ) {
1343 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1344 sorted
[a
[key
]] = o
[a
[key
]];
1350 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1351 * to a query string of the form foo.bar,baz|bar.baz,quux
1354 function buildModulesString( moduleMap
) {
1355 var arr
= [], p
, prefix
;
1356 for ( prefix
in moduleMap
) {
1357 p
= prefix
=== '' ? '' : prefix
+ '.';
1358 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
1360 return arr
.join( '|' );
1364 * Asynchronously append a script tag to the end of the body
1365 * that invokes load.php
1367 * @param {Object} moduleMap Module map, see #buildModulesString
1368 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1369 * @param {string} sourceLoadScript URL of load.php
1370 * @param {boolean} async Whether to load modules asynchronously.
1371 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1373 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
1374 var request
= $.extend(
1375 { modules
: buildModulesString( moduleMap
) },
1378 request
= sortQuery( request
);
1379 // Append &* to avoid triggering the IE6 extension check
1380 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
1383 /* Public Members */
1386 * The module registry is exposed as an aid for debugging and inspecting page
1387 * state; it is not a public interface for modifying the registry.
1393 moduleRegistry
: registry
,
1396 * @inheritdoc #newStyleTag
1399 addStyleTag
: newStyleTag
,
1402 * Batch-request queued dependencies from the server.
1405 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1406 source
, concatSource
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
1407 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1408 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
1410 // Build a list of request parameters common to all requests.
1412 skin
: mw
.config
.get( 'skin' ),
1413 lang
: mw
.config
.get( 'wgUserLanguage' ),
1414 debug
: mw
.config
.get( 'debug' )
1416 // Split module batch by source and by group.
1418 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
1420 // Appends a list of modules from the queue to the batch
1421 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1422 // Only request modules which are registered
1423 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
1424 // Prevent duplicate entries
1425 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1426 batch
[batch
.length
] = queue
[q
];
1427 // Mark registered modules as loading
1428 registry
[queue
[q
]].state
= 'loading';
1433 mw
.loader
.store
.init();
1434 if ( mw
.loader
.store
.enabled
) {
1436 batch
= $.grep( batch
, function ( module
) {
1437 var source
= mw
.loader
.store
.get( module
);
1439 concatSource
.push( source
);
1444 $.globalEval( concatSource
.join( ';' ) );
1447 // Early exit if there's nothing to load...
1448 if ( !batch
.length
) {
1452 // The queue has been processed into the batch, clear up the queue.
1455 // Always order modules alphabetically to help reduce cache
1456 // misses for otherwise identical content.
1459 // Split batch by source and by group.
1460 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1461 bSource
= registry
[batch
[b
]].source
;
1462 bGroup
= registry
[batch
[b
]].group
;
1463 if ( splits
[bSource
] === undefined ) {
1464 splits
[bSource
] = {};
1466 if ( splits
[bSource
][bGroup
] === undefined ) {
1467 splits
[bSource
][bGroup
] = [];
1469 bSourceGroup
= splits
[bSource
][bGroup
];
1470 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1473 // Clear the batch - this MUST happen before we append any
1474 // script elements to the body or it's possible that a script
1475 // will be locally cached, instantly load, and work the batch
1476 // again, all before we've cleared it causing each request to
1477 // include modules which are already loaded.
1480 for ( source
in splits
) {
1482 sourceLoadScript
= sources
[source
].loadScript
;
1484 for ( group
in splits
[source
] ) {
1486 // Cache access to currently selected list of
1487 // modules for this group from this source.
1488 modules
= splits
[source
][group
];
1490 // Calculate the highest timestamp
1492 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
1493 if ( registry
[modules
[g
]].version
> maxVersion
) {
1494 maxVersion
= registry
[modules
[g
]].version
;
1498 currReqBase
= $.extend( { version
: formatVersionNumber( maxVersion
) }, reqBase
);
1499 // For user modules append a user name to the request.
1500 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1501 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1503 currReqBaseLength
= $.param( currReqBase
).length
;
1505 // We may need to split up the request to honor the query string length limit,
1506 // so build it piece by piece.
1507 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1509 moduleMap
= {}; // { prefix: [ suffixes ] }
1511 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1512 // Determine how many bytes this module would add to the query string
1513 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1514 // Note that these substr() calls work even if lastDotIndex == -1
1515 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1516 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
1517 bytesAdded
= moduleMap
[prefix
] !== undefined
1518 ? suffix
.length
+ 3 // '%2C'.length == 3
1519 : modules
[i
].length
+ 3; // '%7C'.length == 3
1521 // If the request would become too long, create a new one,
1522 // but don't create empty requests
1523 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1524 // This request would become too long, create a new one
1525 // and fire off the old one
1526 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1529 l
= currReqBaseLength
+ 9;
1531 if ( moduleMap
[prefix
] === undefined ) {
1532 moduleMap
[prefix
] = [];
1534 moduleMap
[prefix
].push( suffix
);
1535 if ( !registry
[modules
[i
]].async
) {
1536 // If this module is blocking, make the entire request blocking
1537 // This is slightly suboptimal, but in practice mixing of blocking
1538 // and async modules will only occur in debug mode.
1543 // If there's anything left in moduleMap, request that too
1544 if ( !$.isEmptyObject( moduleMap
) ) {
1545 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1552 * Register a source.
1554 * The #work method will use this information to split up requests by source.
1556 * mw.loader.addSource( 'mediawikiwiki', { loadScript: '//www.mediawiki.org/w/load.php' } );
1558 * @param {string} id Short string representing a source wiki, used internally for
1559 * registered modules to indicate where they should be loaded from (usually lowercase a-z).
1560 * @param {Object} props
1561 * @param {string} props.loadScript Url to the load.php entry point of the source wiki.
1564 addSource: function ( id
, props
) {
1566 // Allow multiple additions
1567 if ( typeof id
=== 'object' ) {
1568 for ( source
in id
) {
1569 mw
.loader
.addSource( source
, id
[source
] );
1574 if ( sources
[id
] !== undefined ) {
1575 throw new Error( 'source already registered: ' + id
);
1578 sources
[id
] = props
;
1584 * Register a module, letting the system know about it and its
1585 * properties. Startup modules contain calls to this function.
1587 * @param {string} module Module name
1588 * @param {number} version Module version number as a timestamp (falls backs to 0)
1589 * @param {string|Array|Function} dependencies One string or array of strings of module
1590 * names on which this module depends, or a function that returns that array.
1591 * @param {string} [group=null] Group which the module is in
1592 * @param {string} [source='local'] Name of the source
1594 register: function ( module
, version
, dependencies
, group
, source
) {
1596 // Allow multiple registration
1597 if ( typeof module
=== 'object' ) {
1598 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1599 // module is an array of module names
1600 if ( typeof module
[m
] === 'string' ) {
1601 mw
.loader
.register( module
[m
] );
1602 // module is an array of arrays
1603 } else if ( typeof module
[m
] === 'object' ) {
1604 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1610 if ( typeof module
!== 'string' ) {
1611 throw new Error( 'module must be a string, not a ' + typeof module
);
1613 if ( registry
[module
] !== undefined ) {
1614 throw new Error( 'module already registered: ' + module
);
1616 // List the module as registered
1617 registry
[module
] = {
1618 version
: version
!== undefined ? parseInt( version
, 10 ) : 0,
1620 group
: typeof group
=== 'string' ? group
: null,
1621 source
: typeof source
=== 'string' ? source
: 'local',
1624 if ( typeof dependencies
=== 'string' ) {
1625 // Allow dependencies to be given as a single module name
1626 registry
[module
].dependencies
= [ dependencies
];
1627 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1628 // Allow dependencies to be given as an array of module names
1629 // or a function which returns an array
1630 registry
[module
].dependencies
= dependencies
;
1635 * Implement a module given the components that make up the module.
1637 * When #load or #using requests one or more modules, the server
1638 * response contain calls to this function.
1640 * All arguments are required.
1642 * @param {string} module Name of module
1643 * @param {Function|Array} script Function with module code or Array of URLs to
1644 * be used as the src attribute of a new `<script>` tag.
1645 * @param {Object} style Should follow one of the following patterns:
1647 * { "css": [css, ..] }
1648 * { "url": { <media>: [url, ..] } }
1650 * And for backwards compatibility (needs to be supported forever due to caching):
1653 * { <media>: [url, ..] }
1655 * The reason css strings are not concatenated anymore is bug 31676. We now check
1656 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1658 * @param {Object} msgs List of key/value pairs to be added to mw#messages.
1660 implement: function ( module
, script
, style
, msgs
) {
1662 if ( typeof module
!== 'string' ) {
1663 throw new Error( 'module must be a string, not a ' + typeof module
);
1665 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1666 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1668 if ( !$.isPlainObject( style
) ) {
1669 throw new Error( 'style must be an object, not a ' + typeof style
);
1671 if ( !$.isPlainObject( msgs
) ) {
1672 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1674 // Automatically register module
1675 if ( registry
[module
] === undefined ) {
1676 mw
.loader
.register( module
);
1678 // Check for duplicate implementation
1679 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1680 throw new Error( 'module already implemented: ' + module
);
1682 // Attach components
1683 registry
[module
].script
= script
;
1684 registry
[module
].style
= style
;
1685 registry
[module
].messages
= msgs
;
1686 // The module may already have been marked as erroneous
1687 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1688 registry
[module
].state
= 'loaded';
1689 if ( allReady( registry
[module
].dependencies
) ) {
1696 * Execute a function as soon as one or more required modules are ready.
1698 * Example of inline dependency on OOjs:
1700 * mw.loader.using( 'oojs', function () {
1701 * OO.compare( [ 1 ], [ 1 ] );
1704 * @param {string|Array} dependencies Module name or array of modules names the callback
1705 * dependends on to be ready before executing
1706 * @param {Function} [ready] callback to execute when all dependencies are ready
1707 * @param {Function} [error] callback to execute when if dependencies have a errors
1709 using: function ( dependencies
, ready
, error
) {
1710 var tod
= typeof dependencies
;
1712 if ( tod
!== 'object' && tod
!== 'string' ) {
1713 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1715 // Allow calling with a single dependency as a string
1716 if ( tod
=== 'string' ) {
1717 dependencies
= [ dependencies
];
1719 // Resolve entire dependency map
1720 dependencies
= resolve( dependencies
);
1721 if ( allReady( dependencies
) ) {
1722 // Run ready immediately
1723 if ( $.isFunction( ready
) ) {
1726 } else if ( filter( ['error', 'missing'], dependencies
).length
) {
1727 // Execute error immediately if any dependencies have errors
1728 if ( $.isFunction( error
) ) {
1729 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1733 // Not all dependencies are ready: queue up a request
1734 request( dependencies
, ready
, error
);
1739 * Load an external script or one or more modules.
1741 * @param {string|Array} modules Either the name of a module, array of modules,
1742 * or a URL of an external script or style
1743 * @param {string} [type='text/javascript'] mime-type to use if calling with a URL of an
1744 * external script or style; acceptable values are "text/css" and
1745 * "text/javascript"; if no type is provided, text/javascript is assumed.
1746 * @param {boolean} [async] Whether to load modules asynchronously.
1747 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1748 * Defaults to `true` if loading a URL, `false` otherwise.
1750 load: function ( modules
, type
, async
) {
1751 var filtered
, m
, module
, l
;
1754 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1755 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1757 // Allow calling with an external url or single dependency as a string
1758 if ( typeof modules
=== 'string' ) {
1759 // Support adding arbitrary external scripts
1760 if ( /^(https?:)?\/\//.test( modules
) ) {
1761 if ( async
=== undefined ) {
1762 // Assume async for bug 34542
1765 if ( type
=== 'text/css' ) {
1766 // IE7-8 throws security warnings when inserting a <link> tag
1767 // with a protocol-relative URL set though attributes (instead of
1768 // properties) - when on HTTPS. See also bug 41331.
1769 l
= document
.createElement( 'link' );
1770 l
.rel
= 'stylesheet';
1772 $( 'head' ).append( l
);
1775 if ( type
=== 'text/javascript' || type
=== undefined ) {
1776 addScript( modules
, null, async
);
1780 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1782 // Called with single module
1783 modules
= [ modules
];
1786 // Filter out undefined modules, otherwise resolve() will throw
1787 // an exception for trying to load an undefined module.
1788 // Undefined modules are acceptable here in load(), because load() takes
1789 // an array of unrelated modules, whereas the modules passed to
1790 // using() are related and must all be loaded.
1791 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1792 module
= registry
[modules
[m
]];
1793 if ( module
!== undefined ) {
1794 if ( $.inArray( module
.state
, ['error', 'missing'] ) === -1 ) {
1795 filtered
[filtered
.length
] = modules
[m
];
1800 if ( filtered
.length
=== 0 ) {
1803 // Resolve entire dependency map
1804 filtered
= resolve( filtered
);
1805 // If all modules are ready, nothing to be done
1806 if ( allReady( filtered
) ) {
1809 // If any modules have errors: also quit.
1810 if ( filter( ['error', 'missing'], filtered
).length
) {
1813 // Since some modules are not yet ready, queue up a request.
1814 request( filtered
, undefined, undefined, async
);
1818 * Change the state of one or more modules.
1820 * @param {string|Object} module Module name or object of module name/state pairs
1821 * @param {string} state State name
1823 state: function ( module
, state
) {
1826 if ( typeof module
=== 'object' ) {
1827 for ( m
in module
) {
1828 mw
.loader
.state( m
, module
[m
] );
1832 if ( registry
[module
] === undefined ) {
1833 mw
.loader
.register( module
);
1835 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1836 && registry
[module
].state
!== state
) {
1837 // Make sure pending modules depending on this one get executed if their
1838 // dependencies are now fulfilled!
1839 registry
[module
].state
= state
;
1840 handlePending( module
);
1842 registry
[module
].state
= state
;
1847 * Get the version of a module.
1849 * @param {string} module Name of module to get version for
1850 * @return {string|null} The version, or null if the module (or its version) is not
1853 getVersion: function ( module
) {
1854 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1855 return formatVersionNumber( registry
[module
].version
);
1861 * Get the state of a module.
1863 * @param {string} module Name of module to get state for
1865 getState: function ( module
) {
1866 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1867 return registry
[module
].state
;
1873 * Get the names of all registered modules.
1877 getModuleNames: function () {
1878 return $.map( registry
, function ( i
, key
) {
1884 * @inheritdoc mw.inspect#runReports
1887 inspect: function () {
1888 var args
= slice
.call( arguments
);
1889 mw
.loader
.using( 'mediawiki.inspect', function () {
1890 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
1895 * On browsers that implement the localStorage API, the module store serves as a
1896 * smart complement to the browser cache. Unlike the browser cache, the module store
1897 * can slice a concatenated response from ResourceLoader into its constituent
1898 * modules and cache each of them separately, using each module's versioning scheme
1899 * to determine when the cache should be invalidated.
1902 * @class mw.loader.store
1905 // Whether the store is in use on this page.
1908 // The contents of the store, mapping '[module name]@[version]' keys
1909 // to module implementations.
1913 stats
: { hits
: 0, misses
: 0, expired
: 0 },
1916 * Construct a JSON-serializable object representing the content of the store.
1917 * @return {Object} Module store contents.
1919 toJSON: function () {
1920 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
1924 * Get the localStorage key for the entire module store. The key references
1925 * $wgDBname to prevent clashes between wikis which share a common host.
1927 * @return {string} localStorage item key
1929 getStoreKey: function () {
1930 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
1934 * Get a string key on which to vary the module cache.
1935 * @return {string} String of concatenated vary conditions.
1937 getVary: function () {
1939 mw
.config
.get( 'skin' ),
1940 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
1941 mw
.config
.get( 'wgUserLanguage' )
1946 * Get a string key for a specific module. The key format is '[name]@[version]'.
1948 * @param {string} module Module name
1949 * @return {string|null} Module key or null if module does not exist
1951 getModuleKey: function ( module
) {
1952 return typeof registry
[module
] === 'object' ?
1953 ( module
+ '@' + registry
[module
].version
) : null;
1957 * Initialize the store.
1959 * Retrieves store from localStorage and (if successfully retrieved) decoding
1960 * the stored JSON value to a plain object.
1962 * The try / catch block is used for JSON & localStorage feature detection.
1963 * See the in-line documentation for Modernizr's localStorage feature detection
1964 * code for a full account of why we need a try / catch:
1965 * https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796
1970 if ( mw
.loader
.store
.enabled
!== null ) {
1975 if ( !mw
.config
.get( 'wgResourceLoaderStorageEnabled' ) || mw
.config
.get( 'debug' ) ) {
1976 // Disabled by configuration, or because debug mode is set
1977 mw
.loader
.store
.enabled
= false;
1982 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
1983 // If we get here, localStorage is available; mark enabled
1984 mw
.loader
.store
.enabled
= true;
1985 data
= JSON
.parse( raw
);
1986 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
1987 mw
.loader
.store
.items
= data
.items
;
1992 if ( raw
=== undefined ) {
1993 // localStorage failed; disable store
1994 mw
.loader
.store
.enabled
= false;
1996 mw
.loader
.store
.update();
2001 * Retrieve a module from the store and update cache hit stats.
2003 * @param {string} module Module name
2004 * @return {string|boolean} Module implementation or false if unavailable
2006 get: function ( module
) {
2009 if ( !mw
.loader
.store
.enabled
) {
2013 key
= mw
.loader
.store
.getModuleKey( module
);
2014 if ( key
in mw
.loader
.store
.items
) {
2015 mw
.loader
.store
.stats
.hits
++;
2016 return mw
.loader
.store
.items
[key
];
2018 mw
.loader
.store
.stats
.misses
++;
2023 * Stringify a module and queue it for storage.
2025 * @param {string} module Module name
2026 * @param {Object} descriptor The module's descriptor as set in the registry
2028 set: function ( module
, descriptor
) {
2031 if ( !mw
.loader
.store
.enabled
) {
2035 key
= mw
.loader
.store
.getModuleKey( module
);
2038 // Already stored a copy of this exact version
2039 key
in mw
.loader
.store
.items
||
2040 // Module failed to load
2041 descriptor
.state
!== 'ready' ||
2042 // Unversioned, private, or site-/user-specific
2043 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user', 'site' ] ) !== -1 ) ||
2044 // Partial descriptor
2045 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
, descriptor
.messages
] ) !== -1
2053 JSON
.stringify( module
),
2054 typeof descriptor
.script
=== 'function' ?
2055 String( descriptor
.script
) :
2056 JSON
.stringify( descriptor
.script
),
2057 JSON
.stringify( descriptor
.style
),
2058 JSON
.stringify( descriptor
.messages
)
2060 // Attempted workaround for a possible Opera bug (bug 57567).
2061 // This regex should never match under sane conditions.
2062 if ( /^\s*\(/.test( args
[1] ) ) {
2063 args
[1] = 'function' + args
[1];
2064 log( 'Detected malformed function stringification (bug 57567)' );
2070 mw
.loader
.store
.items
[key
] = 'mw.loader.implement(' + args
.join( ',' ) + ');';
2071 mw
.loader
.store
.update();
2075 * Iterate through the module store, removing any item that does not correspond
2076 * (in name and version) to an item in the module registry.
2078 prune: function () {
2081 if ( !mw
.loader
.store
.enabled
) {
2085 for ( key
in mw
.loader
.store
.items
) {
2086 module
= key
.substring( 0, key
.indexOf( '@' ) );
2087 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2088 mw
.loader
.store
.stats
.expired
++;
2089 delete mw
.loader
.store
.items
[key
];
2095 * Sync modules to localStorage.
2097 * This function debounces localStorage updates. When called multiple times in
2098 * quick succession, the calls are coalesced into a single update operation.
2099 * This allows us to call #update without having to consider the module load
2100 * queue; the call to localStorage.setItem will be naturally deferred until the
2101 * page is quiescent.
2103 * Because localStorage is shared by all pages with the same origin, if multiple
2104 * pages are loaded with different module sets, the possibility exists that
2105 * modules saved by one page will be clobbered by another. But the impact would
2106 * be minor and the problem would be corrected by subsequent page views.
2110 update
: ( function () {
2115 key
= mw
.loader
.store
.getStoreKey();
2117 if ( !mw
.loader
.store
.enabled
) {
2120 mw
.loader
.store
.prune();
2122 // Replacing the content of the module store might fail if the new
2123 // contents would exceed the browser's localStorage size limit. To
2124 // avoid clogging the browser with stale data, always remove the old
2125 // value before attempting to set the new one.
2126 localStorage
.removeItem( key
);
2127 data
= JSON
.stringify( mw
.loader
.store
);
2128 localStorage
.setItem( key
, data
);
2132 return function () {
2133 clearTimeout( timer
);
2134 timer
= setTimeout( flush
, 2000 );
2142 * HTML construction helper functions
2149 * output = Html.element( 'div', {}, new Html.Raw(
2150 * Html.element( 'img', { src: '<' } )
2152 * mw.log( output ); // <div><img src="<"/></div>
2157 html
: ( function () {
2158 function escapeCallback( s
) {
2175 * Escape a string for HTML. Converts special characters to HTML entities.
2177 * mw.html.escape( '< > \' & "' );
2178 * // Returns < > ' & "
2180 * @param {string} s The string to escape
2182 escape: function ( s
) {
2183 return s
.replace( /['"<>&]/g, escapeCallback
);
2187 * Create an HTML element string, with safe escaping.
2189 * @param {string} name The tag name.
2190 * @param {Object} attrs An object with members mapping element names to values
2191 * @param {Mixed} contents The contents of the element. May be either:
2192 * - string: The string is escaped.
2193 * - null or undefined: The short closing form is used, e.g. <br/>.
2194 * - this.Raw: The value attribute is included without escaping.
2195 * - this.Cdata: The value attribute is included, and an exception is
2196 * thrown if it contains an illegal ETAGO delimiter.
2197 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
2199 element: function ( name
, attrs
, contents
) {
2200 var v
, attrName
, s
= '<' + name
;
2202 for ( attrName
in attrs
) {
2203 v
= attrs
[attrName
];
2204 // Convert name=true, to name=name
2208 } else if ( v
=== false ) {
2211 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2213 if ( contents
=== undefined || contents
=== null ) {
2220 switch ( typeof contents
) {
2223 s
+= this.escape( contents
);
2227 // Convert to string
2228 s
+= String( contents
);
2231 if ( contents
instanceof this.Raw
) {
2232 // Raw HTML inclusion
2233 s
+= contents
.value
;
2234 } else if ( contents
instanceof this.Cdata
) {
2236 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2237 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2239 s
+= contents
.value
;
2241 throw new Error( 'mw.html.element: Invalid type of contents' );
2244 s
+= '</' + name
+ '>';
2249 * Wrapper object for raw HTML passed to mw.html.element().
2250 * @class mw.html.Raw
2252 Raw: function ( value
) {
2257 * Wrapper object for CDATA element contents passed to mw.html.element()
2258 * @class mw.html.Cdata
2260 Cdata: function ( value
) {
2266 // Skeleton user object. mediawiki.user.js extends this
2273 * Registry and firing of events.
2275 * MediaWiki has various interface components that are extended, enhanced
2276 * or manipulated in some other way by extensions, gadgets and even
2279 * This framework helps streamlining the timing of when these other
2280 * code paths fire their plugins (instead of using document-ready,
2281 * which can and should be limited to firing only once).
2283 * Features like navigating to other wiki pages, previewing an edit
2284 * and editing itself – without a refresh – can then retrigger these
2285 * hooks accordingly to ensure everything still works as expected.
2289 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2290 * mw.hook( 'wikipage.content' ).fire( $content );
2292 * Handlers can be added and fired for arbitrary event names at any time. The same
2293 * event can be fired multiple times. The last run of an event is memorized
2294 * (similar to `$(document).ready` and `$.Deferred().done`).
2295 * This means if an event is fired, and a handler added afterwards, the added
2296 * function will be fired right away with the last given event data.
2298 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2299 * Thus allowing flexible use and optimal maintainability and authority control.
2300 * You can pass around the `add` and/or `fire` method to another piece of code
2301 * without it having to know the event name (or `mw.hook` for that matter).
2303 * var h = mw.hook( 'bar.ready' );
2304 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2306 * Note: Events are documented with an underscore instead of a dot in the event
2307 * name due to jsduck not supporting dots in that position.
2311 hook
: ( function () {
2315 * Create an instance of mw.hook.
2319 * @param {string} name Name of hook.
2322 return function ( name
) {
2323 var list
= lists
[name
] || ( lists
[name
] = $.Callbacks( 'memory' ) );
2327 * Register a hook handler
2328 * @param {Function...} handler Function to bind.
2334 * Unregister a hook handler
2335 * @param {Function...} handler Function to unbind.
2338 remove
: list
.remove
,
2342 * @param {Mixed...} data
2346 return list
.fireWith( null, slice
.call( arguments
) );
2355 // Alias $j to jQuery for backwards compatibility
2358 // Attach to window and globally alias
2359 window
.mw
= window
.mediaWiki
= mw
;
2361 // Auto-register from pre-loaded startup scripts
2362 if ( jQuery
.isFunction( window
.startUp
) ) {
2364 window
.startUp
= undefined;