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