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