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