Add to/tweak mediawiki and jqueryMsg JS tests, fix comment
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /*
2 * Core MediaWiki JavaScript Library
3 */
4
5 var mw = ( function ( $, undefined ) {
6 'use strict';
7
8 /* Private Members */
9
10 var hasOwn = Object.prototype.hasOwnProperty,
11 slice = Array.prototype.slice;
12
13 /* Object constructors */
14
15 /**
16 * Creates an object that can be read from or written to from prototype functions
17 * that allow both single and multiple variables at once.
18 * @class mw.Map
19 *
20 * @constructor
21 * @param {boolean} global Whether to store the values in the global window
22 * object or a exclusively in the object property 'values'.
23 */
24 function Map( global ) {
25 this.values = global === true ? window : {};
26 return this;
27 }
28
29 Map.prototype = {
30 /**
31 * Get the value of one or multiple a keys.
32 *
33 * If called with no arguments, all values will be returned.
34 *
35 * @param selection mixed String key or array of keys to get values for.
36 * @param fallback mixed Value to use in case key(s) do not exist (optional).
37 * @return mixed If selection was a string returns the value or null,
38 * If selection was an array, returns an object of key/values (value is null if not found),
39 * If selection was not passed or invalid, will return the 'values' object member (be careful as
40 * objects are always passed by reference in JavaScript!).
41 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
42 */
43 get: function ( selection, fallback ) {
44 var results, i;
45 // If we only do this in the `return` block, it'll fail for the
46 // call to get() from the mutli-selection block.
47 fallback = arguments.length > 1 ? fallback : null;
48
49 if ( $.isArray( selection ) ) {
50 selection = slice.call( selection );
51 results = {};
52 for ( i = 0; i < selection.length; i++ ) {
53 results[selection[i]] = this.get( selection[i], fallback );
54 }
55 return results;
56 }
57
58 if ( typeof selection === 'string' ) {
59 if ( !hasOwn.call( this.values, selection ) ) {
60 return fallback;
61 }
62 return this.values[selection];
63 }
64
65 if ( selection === undefined ) {
66 return this.values;
67 }
68
69 // invalid selection key
70 return null;
71 },
72
73 /**
74 * Sets one or multiple key/value pairs.
75 *
76 * @param selection {mixed} String key or array of keys to set values for.
77 * @param value {mixed} Value to set (optional, only in use when key is a string)
78 * @return {Boolean} This returns true on success, false on failure.
79 */
80 set: function ( selection, value ) {
81 var s;
82
83 if ( $.isPlainObject( selection ) ) {
84 for ( s in selection ) {
85 this.values[s] = selection[s];
86 }
87 return true;
88 }
89 if ( typeof selection === 'string' && arguments.length > 1 ) {
90 this.values[selection] = value;
91 return true;
92 }
93 return false;
94 },
95
96 /**
97 * Checks if one or multiple keys exist.
98 *
99 * @param selection {mixed} String key or array of keys to check
100 * @return {boolean} Existence of key(s)
101 */
102 exists: function ( selection ) {
103 var s;
104
105 if ( $.isArray( selection ) ) {
106 for ( s = 0; s < selection.length; s++ ) {
107 if ( typeof selection[s] !== 'string' || !hasOwn.call( this.values, selection[s] ) ) {
108 return false;
109 }
110 }
111 return true;
112 }
113 return typeof selection === 'string' && hasOwn.call( this.values, selection );
114 }
115 };
116
117 /**
118 * Object constructor for messages,
119 * similar to the Message class in MediaWiki PHP.
120 * @class mw.Message
121 *
122 * @constructor
123 * @param {mw.Map} map Message storage
124 * @param {string} key
125 * @param {Array} [parameters]
126 */
127 function Message( map, key, parameters ) {
128 this.format = 'text';
129 this.map = map;
130 this.key = key;
131 this.parameters = parameters === undefined ? [] : slice.call( parameters );
132 return this;
133 }
134
135 Message.prototype = {
136 /**
137 * Simple message parser, does $N replacement and nothing else.
138 *
139 * This may be overridden to provide a more complex message parser.
140 *
141 * The primary override is in mediawiki.jqueryMsg.
142 *
143 * This function will not be called for nonexistent messages.
144 */
145 parser: function () {
146 var parameters = this.parameters;
147 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
148 var index = parseInt( match, 10 ) - 1;
149 return parameters[index] !== undefined ? parameters[index] : '$' + match;
150 } );
151 },
152
153 /**
154 * Appends (does not replace) parameters for replacement to the .parameters property.
155 *
156 * @param {Array} parameters
157 * @chainable
158 */
159 params: function ( parameters ) {
160 var i;
161 for ( i = 0; i < parameters.length; i += 1 ) {
162 this.parameters.push( parameters[i] );
163 }
164 return this;
165 },
166
167 /**
168 * Converts message object to it's string form based on the state of format.
169 *
170 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
171 */
172 toString: function () {
173 var text;
174
175 if ( !this.exists() ) {
176 // Use <key> as text if key does not exist
177 if ( this.format === 'escaped' || this.format === 'parse' ) {
178 // format 'escaped' and 'parse' need to have the brackets and key html escaped
179 return mw.html.escape( '<' + this.key + '>' );
180 }
181 return '<' + this.key + '>';
182 }
183
184 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
185 text = this.parser();
186 }
187
188 if ( this.format === 'escaped' ) {
189 text = this.parser();
190 text = mw.html.escape( text );
191 }
192
193 return text;
194 },
195
196 /**
197 * Changes format to 'parse' and converts message to string
198 *
199 * If jqueryMsg is loaded, this parses the message text from wikitext
200 * (where supported) to HTML
201 *
202 * Otherwise, it is equivalent to plain.
203 *
204 * @return {string} String form of parsed message
205 */
206 parse: function () {
207 this.format = 'parse';
208 return this.toString();
209 },
210
211 /**
212 * Changes format to 'plain' and converts message to string
213 *
214 * This substitutes parameters, but otherwise does not change the
215 * message text.
216 *
217 * @return {string} String form of plain message
218 */
219 plain: function () {
220 this.format = 'plain';
221 return this.toString();
222 },
223
224 /**
225 * Changes format to 'text' and converts message to string
226 *
227 * If jqueryMsg is loaded, {{-transformation is done where supported
228 * (such as {{plural:}}, {{gender:}}, {{int:}}).
229 *
230 * Otherwise, it is equivalent to plain.
231 */
232 text: function () {
233 this.format = 'text';
234 return this.toString();
235 },
236
237 /**
238 * Changes the format to 'escaped' and converts message to string
239 *
240 * This is equivalent to using the 'text' format (see text method), then
241 * HTML-escaping the output.
242 *
243 * @return {string} String form of html escaped message
244 */
245 escaped: function () {
246 this.format = 'escaped';
247 return this.toString();
248 },
249
250 /**
251 * Checks if message exists
252 *
253 * @see mw.Map#exists
254 * @return {boolean}
255 */
256 exists: function () {
257 return this.map.exists( this.key );
258 }
259 };
260
261 /**
262 * @class mw
263 * @alternateClassName mediaWiki
264 * @singleton
265 */
266 return {
267 /* Public Members */
268
269 /**
270 * Dummy function which in debug mode can be replaced with a function that
271 * emulates console.log in console-less environments.
272 */
273 log: function () { },
274
275 // Make the Map constructor publicly available.
276 Map: Map,
277
278 // Make the Message constructor publicly available.
279 Message: Message,
280
281 /**
282 * List of configuration values
283 *
284 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
285 * If `$wgLegacyJavaScriptGlobals` is true, this Map will have its values
286 * in the global window object.
287 * @property
288 */
289 config: null,
290
291 /**
292 * Empty object that plugins can be installed in.
293 * @property
294 */
295 libs: {},
296
297 /* Extension points */
298
299 /**
300 * @property
301 */
302 legacy: {},
303
304 /**
305 * Localization system
306 * @property {mw.Map}
307 */
308 messages: new Map(),
309
310 /* Public Methods */
311
312 /**
313 * Gets a message object, similar to wfMessage().
314 *
315 * @param {string} key Key of message to get
316 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
317 * @return {mw.Message}
318 */
319 message: function ( key ) {
320 // Variadic arguments
321 var parameters = slice.call( arguments, 1 );
322 return new Message( mw.messages, key, parameters );
323 },
324
325 /**
326 * Gets a message string, similar to wfMessage()
327 *
328 * @see mw.Message#toString
329 * @param {string} key Key of message to get
330 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
331 * @return {string}
332 */
333 msg: function ( /* key, parameters... */ ) {
334 return mw.message.apply( mw.message, arguments ).toString();
335 },
336
337 /**
338 * Client-side module loader which integrates with the MediaWiki ResourceLoader
339 * @class mw.loader
340 * @singleton
341 */
342 loader: ( function () {
343
344 /* Private Members */
345
346 /**
347 * Mapping of registered modules
348 *
349 * The jquery module is pre-registered, because it must have already
350 * been provided for this object to have been built, and in debug mode
351 * jquery would have been provided through a unique loader request,
352 * making it impossible to hold back registration of jquery until after
353 * mediawiki.
354 *
355 * For exact details on support for script, style and messages, look at
356 * mw.loader.implement.
357 *
358 * Format:
359 * {
360 * 'moduleName': {
361 * 'version': ############## (unix timestamp),
362 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
363 * 'group': 'somegroup', (or) null,
364 * 'source': 'local', 'someforeignwiki', (or) null
365 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
366 * 'script': ...,
367 * 'style': ...,
368 * 'messages': { 'key': 'value' },
369 * }
370 * }
371 *
372 * @property
373 * @private
374 */
375 var registry = {},
376 //
377 // Mapping of sources, keyed by source-id, values are objects.
378 // Format:
379 // {
380 // 'sourceId': {
381 // 'loadScript': 'http://foo.bar/w/load.php'
382 // }
383 // }
384 //
385 sources = {},
386 // List of modules which will be loaded as when ready
387 batch = [],
388 // List of modules to be loaded
389 queue = [],
390 // List of callback functions waiting for modules to be ready to be called
391 jobs = [],
392 // Selector cache for the marker element. Use getMarker() to get/use the marker!
393 $marker = null,
394 // Buffer for addEmbeddedCSS.
395 cssBuffer = '';
396
397 /* Private methods */
398
399 function getMarker() {
400 // Cached ?
401 if ( $marker ) {
402 return $marker;
403 }
404
405 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
406 if ( $marker.length ) {
407 return $marker;
408 }
409 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
410 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
411
412 return $marker;
413 }
414
415 /**
416 * Create a new style tag and add it to the DOM.
417 *
418 * @private
419 * @param {string} text CSS text
420 * @param {Mixed} [nextnode] An Element or jQuery object for an element where
421 * the style tag should be inserted before. Otherwise appended to the `<head>`.
422 * @return {HTMLElement} Node reference to the created `<style>` tag.
423 */
424 function addStyleTag( text, nextnode ) {
425 var s = document.createElement( 'style' );
426 // Insert into document before setting cssText (bug 33305)
427 if ( nextnode ) {
428 // Must be inserted with native insertBefore, not $.fn.before.
429 // When using jQuery to insert it, like $nextnode.before( s ),
430 // then IE6 will throw "Access is denied" when trying to append
431 // to .cssText later. Some kind of weird security measure.
432 // http://stackoverflow.com/q/12586482/319266
433 // Works: jsfiddle.net/zJzMy/1
434 // Fails: jsfiddle.net/uJTQz
435 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
436 if ( nextnode.jquery ) {
437 nextnode = nextnode.get( 0 );
438 }
439 nextnode.parentNode.insertBefore( s, nextnode );
440 } else {
441 document.getElementsByTagName( 'head' )[0].appendChild( s );
442 }
443 if ( s.styleSheet ) {
444 // IE
445 s.styleSheet.cssText = text;
446 } else {
447 // Other browsers.
448 // (Safari sometimes borks on non-string values,
449 // play safe by casting to a string, just in case.)
450 s.appendChild( document.createTextNode( String( text ) ) );
451 }
452 return s;
453 }
454
455 /**
456 * Checks whether it is safe to add this css to a stylesheet.
457 *
458 * @private
459 * @param {string} cssText
460 * @return {boolean} False if a new one must be created.
461 */
462 function canExpandStylesheetWith( cssText ) {
463 // Makes sure that cssText containing `@import`
464 // rules will end up in a new stylesheet (as those only work when
465 // placed at the start of a stylesheet; bug 35562).
466 return cssText.indexOf( '@import' ) === -1;
467 }
468
469 /**
470 * @param {string} [cssText=cssBuffer] If called without cssText,
471 * the internal buffer will be inserted instead.
472 */
473 function addEmbeddedCSS( cssText ) {
474 var $style, styleEl;
475
476 // Yield once before inserting the <style> tag. There are likely
477 // more calls coming up which we can combine this way.
478 // Appending a stylesheet and waiting for the browser to repaint
479 // is fairly expensive, this reduces it (bug 45810)
480 if ( cssText ) {
481 // Be careful not to extend the buffer with css that needs a new stylesheet
482 if ( !cssBuffer || canExpandStylesheetWith( cssText ) ) {
483 // Linebreak for somewhat distinguishable sections
484 // (the rl-cachekey comment separating each)
485 cssBuffer += '\n' + cssText;
486 // TODO: Use requestAnimationFrame in the future which will
487 // perform even better by not injecting styles while the browser
488 // is paiting.
489 setTimeout( addEmbeddedCSS );
490 return;
491 }
492
493 // This is a delayed call and we got a buffer still
494 } else if ( cssBuffer ) {
495 cssText = cssBuffer;
496 cssBuffer = '';
497 } else {
498 // This is a delayed call, but buffer is already cleared by
499 // another delayed call.
500 return;
501 }
502
503 // By default, always create a new <style>. Appending text
504 // to a <style> tag means the contents have to be re-parsed (bug 45810).
505 // Except, of course, in IE below 9, in there we default to
506 // re-using and appending to a <style> tag due to the
507 // IE stylesheet limit (bug 31676).
508 if ( 'documentMode' in document && document.documentMode <= 9 ) {
509
510 $style = getMarker().prev();
511 // Verify that the the element before Marker actually is a
512 // <style> tag and one that came from ResourceLoader
513 // (not some other style tag or even a `<meta>` or `<script>`).
514 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
515 // There's already a dynamic <style> tag present and
516 // canExpandStylesheetWith() gave a green light to append more to it.
517 styleEl = $style.get( 0 );
518 if ( styleEl.styleSheet ) {
519 try {
520 styleEl.styleSheet.cssText += cssText; // IE
521 } catch ( e ) {
522 log( 'addEmbeddedCSS fail\ne.message: ' + e.message, e );
523 }
524 } else {
525 styleEl.appendChild( document.createTextNode( String( cssText ) ) );
526 }
527 return;
528 }
529 }
530
531 $( addStyleTag( cssText, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
532 }
533
534 /**
535 * Generates an ISO8601 "basic" string from a UNIX timestamp
536 * @private
537 */
538 function formatVersionNumber( timestamp ) {
539 var d = new Date();
540 function pad( a, b, c ) {
541 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
542 }
543 d.setTime( timestamp * 1000 );
544 return [
545 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
546 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
547 ].join( '' );
548 }
549
550 /**
551 * Resolves dependencies and detects circular references.
552 *
553 * @private
554 * @param {string} module Name of the top-level module whose dependencies shall be
555 * resolved and sorted.
556 * @param {Array} resolved Returns a topological sort of the given module and its
557 * dependencies, such that later modules depend on earlier modules. The array
558 * contains the module names. If the array contains already some module names,
559 * this function appends its result to the pre-existing array.
560 * @param {Object} [unresolved] Hash used to track the current dependency
561 * chain; used to report loops in the dependency graph.
562 * @throws {Error} If any unregistered module or a dependency loop is encountered
563 */
564 function sortDependencies( module, resolved, unresolved ) {
565 var n, deps, len;
566
567 if ( registry[module] === undefined ) {
568 throw new Error( 'Unknown dependency: ' + module );
569 }
570 // Resolves dynamic loader function and replaces it with its own results
571 if ( $.isFunction( registry[module].dependencies ) ) {
572 registry[module].dependencies = registry[module].dependencies();
573 // Ensures the module's dependencies are always in an array
574 if ( typeof registry[module].dependencies !== 'object' ) {
575 registry[module].dependencies = [registry[module].dependencies];
576 }
577 }
578 if ( $.inArray( module, resolved ) !== -1 ) {
579 // Module already resolved; nothing to do.
580 return;
581 }
582 // unresolved is optional, supply it if not passed in
583 if ( !unresolved ) {
584 unresolved = {};
585 }
586 // Tracks down dependencies
587 deps = registry[module].dependencies;
588 len = deps.length;
589 for ( n = 0; n < len; n += 1 ) {
590 if ( $.inArray( deps[n], resolved ) === -1 ) {
591 if ( unresolved[deps[n]] ) {
592 throw new Error(
593 'Circular reference detected: ' + module +
594 ' -> ' + deps[n]
595 );
596 }
597
598 // Add to unresolved
599 unresolved[module] = true;
600 sortDependencies( deps[n], resolved, unresolved );
601 delete unresolved[module];
602 }
603 }
604 resolved[resolved.length] = module;
605 }
606
607 /**
608 * Gets a list of module names that a module depends on in their proper dependency
609 * order.
610 *
611 * @private
612 * @param {string} module Module name or array of string module names
613 * @return {Array} list of dependencies, including 'module'.
614 * @throws {Error} If circular reference is detected
615 */
616 function resolve( module ) {
617 var m, resolved;
618
619 // Allow calling with an array of module names
620 if ( $.isArray( module ) ) {
621 resolved = [];
622 for ( m = 0; m < module.length; m += 1 ) {
623 sortDependencies( module[m], resolved );
624 }
625 return resolved;
626 }
627
628 if ( typeof module === 'string' ) {
629 resolved = [];
630 sortDependencies( module, resolved );
631 return resolved;
632 }
633
634 throw new Error( 'Invalid module argument: ' + module );
635 }
636
637 /**
638 * Narrows a list of module names down to those matching a specific
639 * state (see comment on top of this scope for a list of valid states).
640 * One can also filter for 'unregistered', which will return the
641 * modules names that don't have a registry entry.
642 *
643 * @private
644 * @param {string|string[]} states Module states to filter by
645 * @param {Array} modules List of module names to filter (optional, by default the entire
646 * registry is used)
647 * @return {Array} List of filtered module names
648 */
649 function filter( states, modules ) {
650 var list, module, s, m;
651
652 // Allow states to be given as a string
653 if ( typeof states === 'string' ) {
654 states = [states];
655 }
656 // If called without a list of modules, build and use a list of all modules
657 list = [];
658 if ( modules === undefined ) {
659 modules = [];
660 for ( module in registry ) {
661 modules[modules.length] = module;
662 }
663 }
664 // Build a list of modules which are in one of the specified states
665 for ( s = 0; s < states.length; s += 1 ) {
666 for ( m = 0; m < modules.length; m += 1 ) {
667 if ( registry[modules[m]] === undefined ) {
668 // Module does not exist
669 if ( states[s] === 'unregistered' ) {
670 // OK, undefined
671 list[list.length] = modules[m];
672 }
673 } else {
674 // Module exists, check state
675 if ( registry[modules[m]].state === states[s] ) {
676 // OK, correct state
677 list[list.length] = modules[m];
678 }
679 }
680 }
681 }
682 return list;
683 }
684
685 /**
686 * Determine whether all dependencies are in state 'ready', which means we may
687 * execute the module or job now.
688 *
689 * @private
690 * @param {Array} dependencies Dependencies (module names) to be checked.
691 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
692 */
693 function allReady( dependencies ) {
694 return filter( 'ready', dependencies ).length === dependencies.length;
695 }
696
697 /**
698 * Log a message to window.console, if possible. Useful to force logging of some
699 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
700 * Gets console references in each invocation, so that delayed debugging tools work
701 * fine. No need for optimization here, which would only result in losing logs.
702 *
703 * @private
704 * @param {string} msg text for the log entry.
705 * @param {Error} [e]
706 */
707 function log( msg, e ) {
708 var console = window.console;
709 if ( console && console.log ) {
710 console.log( msg );
711 // If we have an exception object, log it through .error() to trigger
712 // proper stacktraces in browsers that support it. There are no (known)
713 // browsers that don't support .error(), that do support .log() and
714 // have useful exception handling through .log().
715 if ( e && console.error ) {
716 console.error( e );
717 }
718 }
719 }
720
721 /**
722 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
723 * and modules that depend upon this module. if the given module failed, propagate the 'error'
724 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
725 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
726 *
727 * @private
728 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
729 */
730 function handlePending( module ) {
731 var j, job, hasErrors, m, stateChange;
732
733 // Modules.
734 if ( $.inArray( registry[module].state, ['error', 'missing'] ) !== -1 ) {
735 // If the current module failed, mark all dependent modules also as failed.
736 // Iterate until steady-state to propagate the error state upwards in the
737 // dependency tree.
738 do {
739 stateChange = false;
740 for ( m in registry ) {
741 if ( $.inArray( registry[m].state, ['error', 'missing'] ) === -1 ) {
742 if ( filter( ['error', 'missing'], registry[m].dependencies ).length > 0 ) {
743 registry[m].state = 'error';
744 stateChange = true;
745 }
746 }
747 }
748 } while ( stateChange );
749 }
750
751 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
752 for ( j = 0; j < jobs.length; j += 1 ) {
753 hasErrors = filter( ['error', 'missing'], jobs[j].dependencies ).length > 0;
754 if ( hasErrors || allReady( jobs[j].dependencies ) ) {
755 // All dependencies satisfied, or some have errors
756 job = jobs[j];
757 jobs.splice( j, 1 );
758 j -= 1;
759 try {
760 if ( hasErrors ) {
761 throw new Error( 'Module ' + module + ' failed.');
762 } else {
763 if ( $.isFunction( job.ready ) ) {
764 job.ready();
765 }
766 }
767 } catch ( e ) {
768 if ( $.isFunction( job.error ) ) {
769 try {
770 job.error( e, [module] );
771 } catch ( ex ) {
772 // A user-defined operation raised an exception. Swallow to protect
773 // our state machine!
774 log( 'Exception thrown by job.error()', ex );
775 }
776 }
777 }
778 }
779 }
780
781 if ( registry[module].state === 'ready' ) {
782 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
783 // and now have all dependencies satisfied.
784 for ( m in registry ) {
785 if ( registry[m].state === 'loaded' && allReady( registry[m].dependencies ) ) {
786 execute( m );
787 }
788 }
789 }
790 }
791
792 /**
793 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
794 * depending on whether document-ready has occurred yet and whether we are in async mode.
795 *
796 * @private
797 * @param {string} src URL to script, will be used as the src attribute in the script tag
798 * @param {Function} [callback] Callback which will be run when the script is done
799 */
800 function addScript( src, callback, async ) {
801 /*jshint evil:true */
802 var script, head,
803 done = false;
804
805 // Using isReady directly instead of storing it locally from
806 // a $.fn.ready callback (bug 31895).
807 if ( $.isReady || async ) {
808 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
809 // it uses XHR and eval for same-domain scripts, which we don't want because it
810 // messes up line numbers.
811 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
812
813 // IE-safe way of getting the <head>. document.head isn't supported
814 // in old IE, and doesn't work when in the <head>.
815 head = document.getElementsByTagName( 'head' )[0] || document.body;
816
817 script = document.createElement( 'script' );
818 script.async = true;
819 script.src = src;
820 if ( $.isFunction( callback ) ) {
821 script.onload = script.onreadystatechange = function () {
822 if (
823 !done
824 && (
825 !script.readyState
826 || /loaded|complete/.test( script.readyState )
827 )
828 ) {
829 done = true;
830
831 // Handle memory leak in IE
832 script.onload = script.onreadystatechange = null;
833
834 // Remove the script
835 if ( script.parentNode ) {
836 script.parentNode.removeChild( script );
837 }
838
839 // Dereference the script
840 script = undefined;
841
842 callback();
843 }
844 };
845 }
846
847 if ( window.opera ) {
848 // Appending to the <head> blocks rendering completely in Opera,
849 // so append to the <body> after document ready. This means the
850 // scripts only start loading after the document has been rendered,
851 // but so be it. Opera users don't deserve faster web pages if their
852 // browser makes it impossible.
853 $( function () {
854 document.body.appendChild( script );
855 } );
856 } else {
857 head.appendChild( script );
858 }
859 } else {
860 document.write( mw.html.element( 'script', { 'src': src }, '' ) );
861 if ( $.isFunction( callback ) ) {
862 // Document.write is synchronous, so this is called when it's done
863 // FIXME: that's a lie. doc.write isn't actually synchronous
864 callback();
865 }
866 }
867 }
868
869 /**
870 * Executes a loaded module, making it ready to use
871 *
872 * @private
873 * @param {string} module Module name to execute
874 */
875 function execute( module ) {
876 var key, value, media, i, urls, script, markModuleReady, nestedAddScript;
877
878 if ( registry[module] === undefined ) {
879 throw new Error( 'Module has not been registered yet: ' + module );
880 } else if ( registry[module].state === 'registered' ) {
881 throw new Error( 'Module has not been requested from the server yet: ' + module );
882 } else if ( registry[module].state === 'loading' ) {
883 throw new Error( 'Module has not completed loading yet: ' + module );
884 } else if ( registry[module].state === 'ready' ) {
885 throw new Error( 'Module has already been loaded: ' + module );
886 }
887
888 /**
889 * Define loop-function here for efficiency
890 * and to avoid re-using badly scoped variables.
891 * @ignore
892 */
893 function addLink( media, url ) {
894 var el = document.createElement( 'link' );
895 getMarker().before( el ); // IE: Insert in dom before setting href
896 el.rel = 'stylesheet';
897 if ( media && media !== 'all' ) {
898 el.media = media;
899 }
900 el.href = url;
901 }
902
903 // Process styles (see also mw.loader.implement)
904 // * back-compat: { <media>: css }
905 // * back-compat: { <media>: [url, ..] }
906 // * { "css": [css, ..] }
907 // * { "url": { <media>: [url, ..] } }
908 if ( $.isPlainObject( registry[module].style ) ) {
909 for ( key in registry[module].style ) {
910 value = registry[module].style[key];
911 media = undefined;
912
913 if ( key !== 'url' && key !== 'css' ) {
914 // Backwards compatibility, key is a media-type
915 if ( typeof value === 'string' ) {
916 // back-compat: { <media>: css }
917 // Ignore 'media' because it isn't supported (nor was it used).
918 // Strings are pre-wrapped in "@media". The media-type was just ""
919 // (because it had to be set to something).
920 // This is one of the reasons why this format is no longer used.
921 addEmbeddedCSS( value );
922 } else {
923 // back-compat: { <media>: [url, ..] }
924 media = key;
925 key = 'bc-url';
926 }
927 }
928
929 // Array of css strings in key 'css',
930 // or back-compat array of urls from media-type
931 if ( $.isArray( value ) ) {
932 for ( i = 0; i < value.length; i += 1 ) {
933 if ( key === 'bc-url' ) {
934 // back-compat: { <media>: [url, ..] }
935 addLink( media, value[i] );
936 } else if ( key === 'css' ) {
937 // { "css": [css, ..] }
938 addEmbeddedCSS( value[i] );
939 }
940 }
941 // Not an array, but a regular object
942 // Array of urls inside media-type key
943 } else if ( typeof value === 'object' ) {
944 // { "url": { <media>: [url, ..] } }
945 for ( media in value ) {
946 urls = value[media];
947 for ( i = 0; i < urls.length; i += 1 ) {
948 addLink( media, urls[i] );
949 }
950 }
951 }
952 }
953 }
954
955 // Add localizations to message system
956 if ( $.isPlainObject( registry[module].messages ) ) {
957 mw.messages.set( registry[module].messages );
958 }
959
960 // Execute script
961 try {
962 script = registry[module].script;
963 markModuleReady = function () {
964 registry[module].state = 'ready';
965 handlePending( module );
966 };
967 nestedAddScript = function ( arr, callback, async, i ) {
968 // Recursively call addScript() in its own callback
969 // for each element of arr.
970 if ( i >= arr.length ) {
971 // We're at the end of the array
972 callback();
973 return;
974 }
975
976 addScript( arr[i], function () {
977 nestedAddScript( arr, callback, async, i + 1 );
978 }, async );
979 };
980
981 if ( $.isArray( script ) ) {
982 registry[module].state = 'loading';
983 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
984 } else if ( $.isFunction( script ) ) {
985 registry[module].state = 'ready';
986 script( $ );
987 handlePending( module );
988 }
989 } catch ( e ) {
990 // This needs to NOT use mw.log because these errors are common in production mode
991 // and not in debug mode, such as when a symbol that should be global isn't exported
992 log( 'Exception thrown by ' + module + ': ' + e.message, e );
993 registry[module].state = 'error';
994 handlePending( module );
995 }
996 }
997
998 /**
999 * Adds a dependencies to the queue with optional callbacks to be run
1000 * when the dependencies are ready or fail
1001 *
1002 * @private
1003 * @param {string|string[]} dependencies Module name or array of string module names
1004 * @param {Function} [ready] Callback to execute when all dependencies are ready
1005 * @param {Function} [error] Callback to execute when any dependency fails
1006 * @param {boolean} [async] If true, load modules asynchronously even if
1007 * document ready has not yet occurred.
1008 */
1009 function request( dependencies, ready, error, async ) {
1010 var n;
1011
1012 // Allow calling by single module name
1013 if ( typeof dependencies === 'string' ) {
1014 dependencies = [dependencies];
1015 }
1016
1017 // Add ready and error callbacks if they were given
1018 if ( ready !== undefined || error !== undefined ) {
1019 jobs[jobs.length] = {
1020 'dependencies': filter(
1021 ['registered', 'loading', 'loaded'],
1022 dependencies
1023 ),
1024 'ready': ready,
1025 'error': error
1026 };
1027 }
1028
1029 // Queue up any dependencies that are registered
1030 dependencies = filter( ['registered'], dependencies );
1031 for ( n = 0; n < dependencies.length; n += 1 ) {
1032 if ( $.inArray( dependencies[n], queue ) === -1 ) {
1033 queue[queue.length] = dependencies[n];
1034 if ( async ) {
1035 // Mark this module as async in the registry
1036 registry[dependencies[n]].async = true;
1037 }
1038 }
1039 }
1040
1041 // Work the queue
1042 mw.loader.work();
1043 }
1044
1045 function sortQuery(o) {
1046 var sorted = {}, key, a = [];
1047 for ( key in o ) {
1048 if ( hasOwn.call( o, key ) ) {
1049 a.push( key );
1050 }
1051 }
1052 a.sort();
1053 for ( key = 0; key < a.length; key += 1 ) {
1054 sorted[a[key]] = o[a[key]];
1055 }
1056 return sorted;
1057 }
1058
1059 /**
1060 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1061 * to a query string of the form foo.bar,baz|bar.baz,quux
1062 * @private
1063 */
1064 function buildModulesString( moduleMap ) {
1065 var arr = [], p, prefix;
1066 for ( prefix in moduleMap ) {
1067 p = prefix === '' ? '' : prefix + '.';
1068 arr.push( p + moduleMap[prefix].join( ',' ) );
1069 }
1070 return arr.join( '|' );
1071 }
1072
1073 /**
1074 * Asynchronously append a script tag to the end of the body
1075 * that invokes load.php
1076 * @private
1077 * @param {Object} moduleMap Module map, see #buildModulesString
1078 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1079 * @param {string} sourceLoadScript URL of load.php
1080 * @param {boolean} async If true, use an asynchrounous request even if document ready has not yet occurred
1081 */
1082 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
1083 var request = $.extend(
1084 { modules: buildModulesString( moduleMap ) },
1085 currReqBase
1086 );
1087 request = sortQuery( request );
1088 // Asynchronously append a script tag to the end of the body
1089 // Append &* to avoid triggering the IE6 extension check
1090 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
1091 }
1092
1093 /* Public Methods */
1094 return {
1095 addStyleTag: addStyleTag,
1096
1097 /**
1098 * Requests dependencies from server, loading and executing when things when ready.
1099 */
1100 work: function () {
1101 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
1102 source, group, g, i, modules, maxVersion, sourceLoadScript,
1103 currReqBase, currReqBaseLength, moduleMap, l,
1104 lastDotIndex, prefix, suffix, bytesAdded, async;
1105
1106 // Build a list of request parameters common to all requests.
1107 reqBase = {
1108 skin: mw.config.get( 'skin' ),
1109 lang: mw.config.get( 'wgUserLanguage' ),
1110 debug: mw.config.get( 'debug' )
1111 };
1112 // Split module batch by source and by group.
1113 splits = {};
1114 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
1115
1116 // Appends a list of modules from the queue to the batch
1117 for ( q = 0; q < queue.length; q += 1 ) {
1118 // Only request modules which are registered
1119 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
1120 // Prevent duplicate entries
1121 if ( $.inArray( queue[q], batch ) === -1 ) {
1122 batch[batch.length] = queue[q];
1123 // Mark registered modules as loading
1124 registry[queue[q]].state = 'loading';
1125 }
1126 }
1127 }
1128 // Early exit if there's nothing to load...
1129 if ( !batch.length ) {
1130 return;
1131 }
1132
1133 // The queue has been processed into the batch, clear up the queue.
1134 queue = [];
1135
1136 // Always order modules alphabetically to help reduce cache
1137 // misses for otherwise identical content.
1138 batch.sort();
1139
1140 // Split batch by source and by group.
1141 for ( b = 0; b < batch.length; b += 1 ) {
1142 bSource = registry[batch[b]].source;
1143 bGroup = registry[batch[b]].group;
1144 if ( splits[bSource] === undefined ) {
1145 splits[bSource] = {};
1146 }
1147 if ( splits[bSource][bGroup] === undefined ) {
1148 splits[bSource][bGroup] = [];
1149 }
1150 bSourceGroup = splits[bSource][bGroup];
1151 bSourceGroup[bSourceGroup.length] = batch[b];
1152 }
1153
1154 // Clear the batch - this MUST happen before we append any
1155 // script elements to the body or it's possible that a script
1156 // will be locally cached, instantly load, and work the batch
1157 // again, all before we've cleared it causing each request to
1158 // include modules which are already loaded.
1159 batch = [];
1160
1161 for ( source in splits ) {
1162
1163 sourceLoadScript = sources[source].loadScript;
1164
1165 for ( group in splits[source] ) {
1166
1167 // Cache access to currently selected list of
1168 // modules for this group from this source.
1169 modules = splits[source][group];
1170
1171 // Calculate the highest timestamp
1172 maxVersion = 0;
1173 for ( g = 0; g < modules.length; g += 1 ) {
1174 if ( registry[modules[g]].version > maxVersion ) {
1175 maxVersion = registry[modules[g]].version;
1176 }
1177 }
1178
1179 currReqBase = $.extend( { version: formatVersionNumber( maxVersion ) }, reqBase );
1180 // For user modules append a user name to the request.
1181 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1182 currReqBase.user = mw.config.get( 'wgUserName' );
1183 }
1184 currReqBaseLength = $.param( currReqBase ).length;
1185 async = true;
1186 // We may need to split up the request to honor the query string length limit,
1187 // so build it piece by piece.
1188 l = currReqBaseLength + 9; // '&modules='.length == 9
1189
1190 moduleMap = {}; // { prefix: [ suffixes ] }
1191
1192 for ( i = 0; i < modules.length; i += 1 ) {
1193 // Determine how many bytes this module would add to the query string
1194 lastDotIndex = modules[i].lastIndexOf( '.' );
1195 // Note that these substr() calls work even if lastDotIndex == -1
1196 prefix = modules[i].substr( 0, lastDotIndex );
1197 suffix = modules[i].substr( lastDotIndex + 1 );
1198 bytesAdded = moduleMap[prefix] !== undefined
1199 ? suffix.length + 3 // '%2C'.length == 3
1200 : modules[i].length + 3; // '%7C'.length == 3
1201
1202 // If the request would become too long, create a new one,
1203 // but don't create empty requests
1204 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1205 // This request would become too long, create a new one
1206 // and fire off the old one
1207 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1208 moduleMap = {};
1209 async = true;
1210 l = currReqBaseLength + 9;
1211 }
1212 if ( moduleMap[prefix] === undefined ) {
1213 moduleMap[prefix] = [];
1214 }
1215 moduleMap[prefix].push( suffix );
1216 if ( !registry[modules[i]].async ) {
1217 // If this module is blocking, make the entire request blocking
1218 // This is slightly suboptimal, but in practice mixing of blocking
1219 // and async modules will only occur in debug mode.
1220 async = false;
1221 }
1222 l += bytesAdded;
1223 }
1224 // If there's anything left in moduleMap, request that too
1225 if ( !$.isEmptyObject( moduleMap ) ) {
1226 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1227 }
1228 }
1229 }
1230 },
1231
1232 /**
1233 * Register a source.
1234 *
1235 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1236 * @param {Object} props Object containing only the loadScript property which is a url to
1237 * the load.php location of the source.
1238 * @return {boolean}
1239 */
1240 addSource: function ( id, props ) {
1241 var source;
1242 // Allow multiple additions
1243 if ( typeof id === 'object' ) {
1244 for ( source in id ) {
1245 mw.loader.addSource( source, id[source] );
1246 }
1247 return true;
1248 }
1249
1250 if ( sources[id] !== undefined ) {
1251 throw new Error( 'source already registered: ' + id );
1252 }
1253
1254 sources[id] = props;
1255
1256 return true;
1257 },
1258
1259 /**
1260 * Registers a module, letting the system know about it and its
1261 * properties. Startup modules contain calls to this function.
1262 *
1263 * @param module {String}: Module name
1264 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1265 * @param dependencies {String|Array|Function}: One string or array of strings of module
1266 * names on which this module depends, or a function that returns that array.
1267 * @param group {String}: Group which the module is in (optional, defaults to null)
1268 * @param source {String}: Name of the source. Defaults to local.
1269 */
1270 register: function ( module, version, dependencies, group, source ) {
1271 var m;
1272 // Allow multiple registration
1273 if ( typeof module === 'object' ) {
1274 for ( m = 0; m < module.length; m += 1 ) {
1275 // module is an array of module names
1276 if ( typeof module[m] === 'string' ) {
1277 mw.loader.register( module[m] );
1278 // module is an array of arrays
1279 } else if ( typeof module[m] === 'object' ) {
1280 mw.loader.register.apply( mw.loader, module[m] );
1281 }
1282 }
1283 return;
1284 }
1285 // Validate input
1286 if ( typeof module !== 'string' ) {
1287 throw new Error( 'module must be a string, not a ' + typeof module );
1288 }
1289 if ( registry[module] !== undefined ) {
1290 throw new Error( 'module already registered: ' + module );
1291 }
1292 // List the module as registered
1293 registry[module] = {
1294 version: version !== undefined ? parseInt( version, 10 ) : 0,
1295 dependencies: [],
1296 group: typeof group === 'string' ? group : null,
1297 source: typeof source === 'string' ? source: 'local',
1298 state: 'registered'
1299 };
1300 if ( typeof dependencies === 'string' ) {
1301 // Allow dependencies to be given as a single module name
1302 registry[module].dependencies = [ dependencies ];
1303 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1304 // Allow dependencies to be given as an array of module names
1305 // or a function which returns an array
1306 registry[module].dependencies = dependencies;
1307 }
1308 },
1309
1310 /**
1311 * Implements a module, giving the system a course of action to take
1312 * upon loading. Results of a request for one or more modules contain
1313 * calls to this function.
1314 *
1315 * All arguments are required.
1316 *
1317 * @param {string} module Name of module
1318 * @param {Function|Array} script Function with module code or Array of URLs to
1319 * be used as the src attribute of a new `<script>` tag.
1320 * @param {Object} style Should follow one of the following patterns:
1321 * { "css": [css, ..] }
1322 * { "url": { <media>: [url, ..] } }
1323 * And for backwards compatibility (needs to be supported forever due to caching):
1324 * { <media>: css }
1325 * { <media>: [url, ..] }
1326 *
1327 * The reason css strings are not concatenated anymore is bug 31676. We now check
1328 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1329 *
1330 * @param {Object} msgs List of key/value pairs to be added to {@link mw#messages}.
1331 */
1332 implement: function ( module, script, style, msgs ) {
1333 // Validate input
1334 if ( typeof module !== 'string' ) {
1335 throw new Error( 'module must be a string, not a ' + typeof module );
1336 }
1337 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1338 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1339 }
1340 if ( !$.isPlainObject( style ) ) {
1341 throw new Error( 'style must be an object, not a ' + typeof style );
1342 }
1343 if ( !$.isPlainObject( msgs ) ) {
1344 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1345 }
1346 // Automatically register module
1347 if ( registry[module] === undefined ) {
1348 mw.loader.register( module );
1349 }
1350 // Check for duplicate implementation
1351 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1352 throw new Error( 'module already implemented: ' + module );
1353 }
1354 // Attach components
1355 registry[module].script = script;
1356 registry[module].style = style;
1357 registry[module].messages = msgs;
1358 // The module may already have been marked as erroneous
1359 if ( $.inArray( registry[module].state, ['error', 'missing'] ) === -1 ) {
1360 registry[module].state = 'loaded';
1361 if ( allReady( registry[module].dependencies ) ) {
1362 execute( module );
1363 }
1364 }
1365 },
1366
1367 /**
1368 * Executes a function as soon as one or more required modules are ready
1369 *
1370 * @param dependencies {String|Array} Module name or array of modules names the callback
1371 * dependends on to be ready before executing
1372 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1373 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1374 */
1375 using: function ( dependencies, ready, error ) {
1376 var tod = typeof dependencies;
1377 // Validate input
1378 if ( tod !== 'object' && tod !== 'string' ) {
1379 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1380 }
1381 // Allow calling with a single dependency as a string
1382 if ( tod === 'string' ) {
1383 dependencies = [ dependencies ];
1384 }
1385 // Resolve entire dependency map
1386 dependencies = resolve( dependencies );
1387 if ( allReady( dependencies ) ) {
1388 // Run ready immediately
1389 if ( $.isFunction( ready ) ) {
1390 ready();
1391 }
1392 } else if ( filter( ['error', 'missing'], dependencies ).length ) {
1393 // Execute error immediately if any dependencies have errors
1394 if ( $.isFunction( error ) ) {
1395 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1396 dependencies );
1397 }
1398 } else {
1399 // Not all dependencies are ready: queue up a request
1400 request( dependencies, ready, error );
1401 }
1402 },
1403
1404 /**
1405 * Loads an external script or one or more modules for future use
1406 *
1407 * @param modules {mixed} Either the name of a module, array of modules,
1408 * or a URL of an external script or style
1409 * @param type {String} mime-type to use if calling with a URL of an
1410 * external script or style; acceptable values are "text/css" and
1411 * "text/javascript"; if no type is provided, text/javascript is assumed.
1412 * @param async {Boolean} (optional) If true, load modules asynchronously
1413 * even if document ready has not yet occurred. If false (default),
1414 * block before document ready and load async after. If not set, true will
1415 * be assumed if loading a URL, and false will be assumed otherwise.
1416 */
1417 load: function ( modules, type, async ) {
1418 var filtered, m, module, l;
1419
1420 // Validate input
1421 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1422 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1423 }
1424 // Allow calling with an external url or single dependency as a string
1425 if ( typeof modules === 'string' ) {
1426 // Support adding arbitrary external scripts
1427 if ( /^(https?:)?\/\//.test( modules ) ) {
1428 if ( async === undefined ) {
1429 // Assume async for bug 34542
1430 async = true;
1431 }
1432 if ( type === 'text/css' ) {
1433 // IE7-8 throws security warnings when inserting a <link> tag
1434 // with a protocol-relative URL set though attributes (instead of
1435 // properties) - when on HTTPS. See also bug #.
1436 l = document.createElement( 'link' );
1437 l.rel = 'stylesheet';
1438 l.href = modules;
1439 $( 'head' ).append( l );
1440 return;
1441 }
1442 if ( type === 'text/javascript' || type === undefined ) {
1443 addScript( modules, null, async );
1444 return;
1445 }
1446 // Unknown type
1447 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1448 }
1449 // Called with single module
1450 modules = [ modules ];
1451 }
1452
1453 // Filter out undefined modules, otherwise resolve() will throw
1454 // an exception for trying to load an undefined module.
1455 // Undefined modules are acceptable here in load(), because load() takes
1456 // an array of unrelated modules, whereas the modules passed to
1457 // using() are related and must all be loaded.
1458 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1459 module = registry[modules[m]];
1460 if ( module !== undefined ) {
1461 if ( $.inArray( module.state, ['error', 'missing'] ) === -1 ) {
1462 filtered[filtered.length] = modules[m];
1463 }
1464 }
1465 }
1466
1467 if ( filtered.length === 0 ) {
1468 return;
1469 }
1470 // Resolve entire dependency map
1471 filtered = resolve( filtered );
1472 // If all modules are ready, nothing to be done
1473 if ( allReady( filtered ) ) {
1474 return;
1475 }
1476 // If any modules have errors: also quit.
1477 if ( filter( ['error', 'missing'], filtered ).length ) {
1478 return;
1479 }
1480 // Since some modules are not yet ready, queue up a request.
1481 request( filtered, undefined, undefined, async );
1482 },
1483
1484 /**
1485 * Changes the state of a module
1486 *
1487 * @param module {String|Object} module name or object of module name/state pairs
1488 * @param state {String} state name
1489 */
1490 state: function ( module, state ) {
1491 var m;
1492
1493 if ( typeof module === 'object' ) {
1494 for ( m in module ) {
1495 mw.loader.state( m, module[m] );
1496 }
1497 return;
1498 }
1499 if ( registry[module] === undefined ) {
1500 mw.loader.register( module );
1501 }
1502 if ( $.inArray( state, ['ready', 'error', 'missing'] ) !== -1
1503 && registry[module].state !== state ) {
1504 // Make sure pending modules depending on this one get executed if their
1505 // dependencies are now fulfilled!
1506 registry[module].state = state;
1507 handlePending( module );
1508 } else {
1509 registry[module].state = state;
1510 }
1511 },
1512
1513 /**
1514 * Gets the version of a module
1515 *
1516 * @param module string name of module to get version for
1517 */
1518 getVersion: function ( module ) {
1519 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1520 return formatVersionNumber( registry[module].version );
1521 }
1522 return null;
1523 },
1524
1525 /**
1526 * @deprecated since 1.18 use mw.loader.getVersion() instead
1527 */
1528 version: function () {
1529 return mw.loader.getVersion.apply( mw.loader, arguments );
1530 },
1531
1532 /**
1533 * Gets the state of a module
1534 *
1535 * @param module string name of module to get state for
1536 */
1537 getState: function ( module ) {
1538 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1539 return registry[module].state;
1540 }
1541 return null;
1542 },
1543
1544 /**
1545 * Get names of all registered modules.
1546 *
1547 * @return {Array}
1548 */
1549 getModuleNames: function () {
1550 return $.map( registry, function ( i, key ) {
1551 return key;
1552 } );
1553 },
1554
1555 /**
1556 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1557 */
1558 go: function () {
1559 mw.loader.load( 'mediawiki.user' );
1560 }
1561 };
1562 }() ),
1563
1564 /**
1565 * HTML construction helper functions
1566 * @class mw.html
1567 * @singleton
1568 */
1569 html: ( function () {
1570 function escapeCallback( s ) {
1571 switch ( s ) {
1572 case '\'':
1573 return '&#039;';
1574 case '"':
1575 return '&quot;';
1576 case '<':
1577 return '&lt;';
1578 case '>':
1579 return '&gt;';
1580 case '&':
1581 return '&amp;';
1582 }
1583 }
1584
1585 return {
1586 /**
1587 * Escape a string for HTML. Converts special characters to HTML entities.
1588 * @param {string} s The string to escape
1589 */
1590 escape: function ( s ) {
1591 return s.replace( /['"<>&]/g, escapeCallback );
1592 },
1593
1594 /**
1595 * Wrapper object for raw HTML passed to mw.html.element().
1596 * @class mw.html.Raw
1597 */
1598 Raw: function ( value ) {
1599 this.value = value;
1600 },
1601
1602 /**
1603 * Wrapper object for CDATA element contents passed to mw.html.element()
1604 * @class mw.html.Cdata
1605 */
1606 Cdata: function ( value ) {
1607 this.value = value;
1608 },
1609
1610 /**
1611 * Create an HTML element string, with safe escaping.
1612 *
1613 * @param name The tag name.
1614 * @param attrs An object with members mapping element names to values
1615 * @param contents The contents of the element. May be either:
1616 * - string: The string is escaped.
1617 * - null or undefined: The short closing form is used, e.g. <br/>.
1618 * - this.Raw: The value attribute is included without escaping.
1619 * - this.Cdata: The value attribute is included, and an exception is
1620 * thrown if it contains an illegal ETAGO delimiter.
1621 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1622 *
1623 * Example:
1624 * var h = mw.html;
1625 * return h.element( 'div', {},
1626 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1627 * Returns <div><img src="&lt;"/></div>
1628 */
1629 element: function ( name, attrs, contents ) {
1630 var v, attrName, s = '<' + name;
1631
1632 for ( attrName in attrs ) {
1633 v = attrs[attrName];
1634 // Convert name=true, to name=name
1635 if ( v === true ) {
1636 v = attrName;
1637 // Skip name=false
1638 } else if ( v === false ) {
1639 continue;
1640 }
1641 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1642 }
1643 if ( contents === undefined || contents === null ) {
1644 // Self close tag
1645 s += '/>';
1646 return s;
1647 }
1648 // Regular open tag
1649 s += '>';
1650 switch ( typeof contents ) {
1651 case 'string':
1652 // Escaped
1653 s += this.escape( contents );
1654 break;
1655 case 'number':
1656 case 'boolean':
1657 // Convert to string
1658 s += String( contents );
1659 break;
1660 default:
1661 if ( contents instanceof this.Raw ) {
1662 // Raw HTML inclusion
1663 s += contents.value;
1664 } else if ( contents instanceof this.Cdata ) {
1665 // CDATA
1666 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1667 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1668 }
1669 s += contents.value;
1670 } else {
1671 throw new Error( 'mw.html.element: Invalid type of contents' );
1672 }
1673 }
1674 s += '</' + name + '>';
1675 return s;
1676 }
1677 };
1678 }() ),
1679
1680 // Skeleton user object. mediawiki.user.js extends this
1681 user: {
1682 options: new Map(),
1683 tokens: new Map()
1684 }
1685 };
1686
1687 }( jQuery ) );
1688
1689 // Alias $j to jQuery for backwards compatibility
1690 window.$j = jQuery;
1691
1692 // Attach to window and globally alias
1693 window.mw = window.mediaWiki = mw;
1694
1695 // Auto-register from pre-loaded startup scripts
1696 if ( jQuery.isFunction( window.startUp ) ) {
1697 window.startUp();
1698 window.startUp = undefined;
1699 }