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