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