More mediawiki.js cleanup
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /*
2 * Core MediaWiki JavaScript Library
3 */
4
5 // Attach to window and globally alias
6 window.mw = window.mediaWiki = new ( function( $ ) {
7
8 /* Private Members */
9
10 /**
11 * @var object List of messages that have been requested to be loaded.
12 */
13 var messageQueue = {};
14
15 /* Object constructors */
16
17 /**
18 * Map
19 *
20 * Creates an object that can be read from or written to from prototype functions
21 * that allow both single and multiple variables at once.
22 *
23 * @param global boolean Whether to store the values in the global window
24 * object or a exclusively in the object property 'values'.
25 * @return Map
26 */
27 function Map( global ) {
28 this.values = ( global === true ) ? window : {};
29 return this;
30 }
31
32 Map.prototype = {
33 /**
34 * Get the value of one or multiple a keys.
35 *
36 * If called with no arguments, all values will be returned.
37 *
38 * @param selection mixed String key or array of keys to get values for.
39 * @param fallback mixed Value to use in case key(s) do not exist (optional).
40 * @return mixed If selection was a string returns the value or null,
41 * If selection was an array, returns an object of key/values (value is null if not found),
42 * If selection was not passed or invalid, will return the 'values' object member (be careful as
43 * objects are always passed by reference in JavaScript!).
44 * @return Values as a string or object, null if invalid/inexistant.
45 */
46 get: function( selection, fallback ) {
47 if ( $.isArray( selection ) ) {
48 selection = $.makeArray( selection );
49 var results = {};
50 for ( var i = 0; i < selection.length; i++ ) {
51 results[selection[i]] = this.get( selection[i], fallback );
52 }
53 return results;
54 } else if ( typeof selection === 'string' ) {
55 if ( this.values[selection] === undefined ) {
56 if ( fallback !== undefined ) {
57 return fallback;
58 }
59 return null;
60 }
61 return this.values[selection];
62 }
63 if ( selection === undefined ) {
64 return this.values;
65 } else {
66 return null; // invalid selection key
67 }
68 },
69
70 /**
71 * Sets one or multiple key/value pairs.
72 *
73 * @param selection mixed String key or array of keys to set values for.
74 * @param value mixed Value to set (optional, only in use when key is a string)
75 * @return bool This returns true on success, false on failure.
76 */
77 set: function( selection, value ) {
78 if ( $.isPlainObject( selection ) ) {
79 for ( var 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 if ( typeof selection === 'object' ) {
98 for ( var s = 0; s < selection.length; s++ ) {
99 if ( !( selection[s] in this.values ) ) {
100 return false;
101 }
102 }
103 return true;
104 } else {
105 return selection in this.values;
106 }
107 }
108 };
109
110 /**
111 * Message
112 *
113 * Object constructor for messages,
114 * similar to the Message class in MediaWiki PHP.
115 *
116 * @param map Map Instance of mw.Map
117 * @param key String
118 * @param parameters Array
119 * @return Message
120 */
121 function Message( map, key, parameters ) {
122 this.format = 'parse';
123 this.map = map;
124 this.key = key;
125 this.parameters = parameters === undefined ? [] : $.makeArray( parameters );
126 return this;
127 }
128
129 Message.prototype = {
130 /**
131 * Appends (does not replace) parameters for replacement to the .parameters property.
132 *
133 * @param parameters Array
134 * @return Message
135 */
136 params: function( parameters ) {
137 for ( var i = 0; i < parameters.length; i++ ) {
138 this.parameters.push( parameters[i] );
139 }
140 return this;
141 },
142
143 /**
144 * Converts message object to it's string form based on the state of format.
145 *
146 * @return string Message as a string in the current form or <key> if key does not exist.
147 */
148 toString: function() {
149 if ( !this.map.exists( this.key ) ) {
150 // Return <key> if key does not exist
151 return '<' + this.key + '>';
152 }
153 var text = this.map.get( this.key ),
154 parameters = this.parameters;
155
156 text = text.replace( /\$(\d+)/g, function( string, match ) {
157 var index = parseInt( match, 10 ) - 1;
158 return index in parameters ? parameters[index] : '$' + match;
159 } );
160
161 if ( this.format === 'plain' ) {
162 return text;
163 }
164 if ( this.format === 'escaped' ) {
165 // According to Message.php this needs {{-transformation, which is
166 // still todo
167 return mw.html.escape( text );
168 }
169
170 /* This should be fixed up when we have a parser
171 if ( this.format === 'parse' && 'language' in mw ) {
172 text = mw.language.parse( text );
173 }
174 */
175 return text;
176 },
177
178 /**
179 * Changes format to parse and converts message to string
180 *
181 * @return {string} String form of parsed message
182 */
183 parse: function() {
184 this.format = 'parse';
185 return this.toString();
186 },
187
188 /**
189 * Changes format to plain and converts message to string
190 *
191 * @return {string} String form of plain message
192 */
193 plain: function() {
194 this.format = 'plain';
195 return this.toString();
196 },
197
198 /**
199 * Changes the format to html escaped and converts message to string
200 *
201 * @return {string} String form of html escaped message
202 */
203 escaped: function() {
204 this.format = 'escaped';
205 return this.toString();
206 },
207
208 /**
209 * Checks if message exists
210 *
211 * @return {string} String form of parsed message
212 */
213 exists: function() {
214 return this.map.exists( this.key );
215 }
216 };
217
218 /* Public Members */
219
220 /*
221 * Dummy function which in debug mode can be replaced with a function that
222 * emulates console.log in console-less environments.
223 */
224 this.log = function() { };
225
226 /**
227 * @var constructor Make the Map constructor publicly available.
228 */
229 this.Map = Map;
230
231 /**
232 * List of configuration values
233 *
234 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
235 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
236 * in the global window object.
237 */
238 this.config = null;
239
240 /**
241 * @var object
242 *
243 * Empty object that plugins can be installed in.
244 */
245 this.libs = {};
246
247 /*
248 * Localization system
249 */
250 this.messages = new this.Map();
251
252 /* Public Methods */
253
254 /**
255 * Gets a message object, similar to wfMessage()
256 *
257 * @param key string Key of message to get
258 * @param parameter_1 mixed First argument in a list of variadic arguments,
259 * each a parameter for $N replacement in messages.
260 * @return Message
261 */
262 this.message = function( key, parameter_1 /* [, parameter_2] */ ) {
263 var parameters;
264 // Support variadic arguments
265 if ( parameter_1 !== undefined ) {
266 parameters = $.makeArray( arguments );
267 parameters.shift();
268 } else {
269 parameters = [];
270 }
271 return new Message( mw.messages, key, parameters );
272 };
273
274 /**
275 * Gets a message string, similar to wfMsg()
276 *
277 * @param key string Key of message to get
278 * @param parameters mixed First argument in a list of variadic arguments,
279 * each a parameter for $N replacement in messages.
280 * @return String.
281 */
282 this.msg = function( key, parameters ) {
283 return mw.message.apply( mw.message, arguments ).toString();
284 };
285
286 /**
287 * Client-side module loader which integrates with the MediaWiki ResourceLoader
288 */
289 this.loader = new ( function() {
290
291 /* Private Members */
292
293 /**
294 * Mapping of registered modules
295 *
296 * The jquery module is pre-registered, because it must have already
297 * been provided for this object to have been built, and in debug mode
298 * jquery would have been provided through a unique loader request,
299 * making it impossible to hold back registration of jquery until after
300 * mediawiki.
301 *
302 * Format:
303 * {
304 * 'moduleName': {
305 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
306 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
307 * 'script': function() {},
308 * 'style': 'css code string',
309 * 'messages': { 'key': 'value' },
310 * 'version': ############## (unix timestamp)
311 * }
312 */
313 var registry = {},
314 // List of modules which will be loaded as when ready
315 batch = [],
316 // List of modules to be loaded
317 queue = [],
318 // List of callback functions waiting for modules to be ready to be called
319 jobs = [],
320 // Flag inidicating that document ready has occured
321 ready = false,
322 // Selector cache for the marker element. Use getMarker() to get/use the marker!
323 $marker = null;
324
325 /* Private Methods */
326
327 function getMarker(){
328 // Cached ?
329 if ( $marker ) {
330 return $marker;
331 } else {
332 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
333 if ( $marker.length ) {
334 return $marker;
335 }
336 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
337 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
338 return $marker;
339 }
340 }
341
342 function compare( a, b ) {
343 if ( a.length !== b.length ) {
344 return false;
345 }
346 for ( var i = 0; i < b.length; i++ ) {
347 if ( $.isArray( a[i] ) ) {
348 if ( !compare( a[i], b[i] ) ) {
349 return false;
350 }
351 }
352 if ( a[i] !== b[i] ) {
353 return false;
354 }
355 }
356 return true;
357 }
358
359 /**
360 * Generates an ISO8601 "basic" string from a UNIX timestamp
361 */
362 function formatVersionNumber( timestamp ) {
363 var pad = function( a, b, c ) {
364 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
365 },
366 d = new Date();
367 d.setTime( timestamp * 1000 );
368 return [
369 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
370 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
371 ].join( '' );
372 }
373
374 /**
375 * Recursively resolves dependencies and detects circular references
376 */
377 function recurse( module, resolved, unresolved ) {
378 if ( registry[module] === undefined ) {
379 throw new Error( 'Unknown dependency: ' + module );
380 }
381 // Resolves dynamic loader function and replaces it with its own results
382 if ( $.isFunction( registry[module].dependencies ) ) {
383 registry[module].dependencies = registry[module].dependencies();
384 // Ensures the module's dependencies are always in an array
385 if ( typeof registry[module].dependencies !== 'object' ) {
386 registry[module].dependencies = [registry[module].dependencies];
387 }
388 }
389 // Tracks down dependencies
390 for ( var n = 0; n < registry[module].dependencies.length; n++ ) {
391 if ( $.inArray( registry[module].dependencies[n], resolved ) === -1 ) {
392 if ( $.inArray( registry[module].dependencies[n], unresolved ) !== -1 ) {
393 throw new Error(
394 'Circular reference detected: ' + module +
395 ' -> ' + registry[module].dependencies[n]
396 );
397 }
398 recurse( registry[module].dependencies[n], resolved, unresolved );
399 }
400 }
401 resolved[resolved.length] = module;
402 unresolved.splice( $.inArray( module, unresolved ), 1 );
403 }
404
405 /**
406 * Gets a list of module names that a module depends on in their proper dependency order
407 *
408 * @param module string module name or array of string module names
409 * @return list of dependencies
410 * @throws Error if circular reference is detected
411 */
412 function resolve( module ) {
413 // Allow calling with an array of module names
414 if ( typeof module === 'object' ) {
415 var modules = [];
416 for ( var m = 0; m < module.length; m++ ) {
417 var dependencies = resolve( module[m] );
418 for ( var n = 0; n < dependencies.length; n++ ) {
419 modules[modules.length] = dependencies[n];
420 }
421 }
422 return modules;
423 } else if ( typeof module === 'string' ) {
424 // Undefined modules have no dependencies
425 if ( !( module in registry ) ) {
426 return [];
427 }
428 var resolved = [];
429 recurse( module, resolved, [] );
430 return resolved;
431 }
432 throw new Error( 'Invalid module argument: ' + module );
433 }
434
435 /**
436 * Narrows a list of module names down to those matching a specific
437 * state. Possible states are 'undefined', 'registered', 'loading',
438 * 'loaded', or 'ready'
439 *
440 * @param states string or array of strings of module states to filter by
441 * @param modules array list of module names to filter (optional, all modules
442 * will be used by default)
443 * @return array list of filtered module names
444 */
445 function filter( states, modules ) {
446 // Allow states to be given as a string
447 if ( typeof states === 'string' ) {
448 states = [states];
449 }
450 // If called without a list of modules, build and use a list of all modules
451 var list = [], module;
452 if ( modules === undefined ) {
453 modules = [];
454 for ( module in registry ) {
455 modules[modules.length] = module;
456 }
457 }
458 // Build a list of modules which are in one of the specified states
459 for ( var s = 0; s < states.length; s++ ) {
460 for ( var m = 0; m < modules.length; m++ ) {
461 if ( registry[modules[m]] === undefined ) {
462 // Module does not exist
463 if ( states[s] === 'undefined' ) {
464 // OK, undefined
465 list[list.length] = modules[m];
466 }
467 } else {
468 // Module exists, check state
469 if ( registry[modules[m]].state === states[s] ) {
470 // OK, correct state
471 list[list.length] = modules[m];
472 }
473 }
474 }
475 }
476 return list;
477 }
478
479 /**
480 * Executes a loaded module, making it ready to use
481 *
482 * @param module string module name to execute
483 */
484 function execute( module, callback ) {
485 if ( registry[module] === undefined ) {
486 throw new Error( 'Module has not been registered yet: ' + module );
487 } else if ( registry[module].state === 'registered' ) {
488 throw new Error( 'Module has not been requested from the server yet: ' + module );
489 } else if ( registry[module].state === 'loading' ) {
490 throw new Error( 'Module has not completed loading yet: ' + module );
491 } else if ( registry[module].state === 'ready' ) {
492 throw new Error( 'Module has already been loaded: ' + module );
493 }
494 // Add styles
495 var style;
496 if ( $.isPlainObject( registry[module].style ) ) {
497 for ( var media in registry[module].style ) {
498 style = registry[module].style[media];
499 if ( $.isArray( style ) ) {
500 for ( var i = 0; i < style.length; i++ ) {
501 getMarker().before( mw.html.element( 'link', {
502 'type': 'text/css',
503 'rel': 'stylesheet',
504 'href': style[i]
505 } ) );
506 }
507 } else if ( typeof style === 'string' ) {
508 getMarker().before( mw.html.element( 'style', {
509 'type': 'text/css',
510 'media': media
511 }, new mw.html.Cdata( style ) ) );
512 }
513 }
514 }
515 // Add localizations to message system
516 if ( $.isPlainObject( registry[module].messages ) ) {
517 mw.messages.set( registry[module].messages );
518 }
519 // Execute script
520 try {
521 var script = registry[module].script,
522 markModuleReady = function() {
523 registry[module].state = 'ready';
524 handlePending( module );
525 if ( $.isFunction( callback ) ) {
526 callback();
527 }
528 };
529
530 if ( $.isArray( script ) ) {
531 var done = 0;
532 if ( script.length === 0 ) {
533 // No scripts in this module? Let's dive out early.
534 markModuleReady();
535 }
536 for ( var i = 0; i < script.length; i++ ) {
537 registry[module].state = 'loading';
538 addScript( script[i], function() {
539 if ( ++done === script.length ) {
540 markModuleReady();
541 }
542 } );
543 }
544 } else if ( $.isFunction( script ) ) {
545 script( jQuery );
546 markModuleReady();
547 }
548 } catch ( e ) {
549 // This needs to NOT use mw.log because these errors are common in production mode
550 // and not in debug mode, such as when a symbol that should be global isn't exported
551 if ( window.console && typeof window.console.log === 'function' ) {
552 console.log( 'mw.loader::execute> Exception thrown by ' + module + ': ' + e.message );
553 }
554 registry[module].state = 'error';
555 throw e;
556 }
557 }
558
559 /**
560 * Automatically executes jobs and modules which are pending with satistifed dependencies.
561 *
562 * This is used when dependencies are satisfied, such as when a module is executed.
563 */
564 function handlePending( module ) {
565 try {
566 // Run jobs who's dependencies have just been met
567 for ( var j = 0; j < jobs.length; j++ ) {
568 if ( compare(
569 filter( 'ready', jobs[j].dependencies ),
570 jobs[j].dependencies ) )
571 {
572 if ( $.isFunction( jobs[j].ready ) ) {
573 jobs[j].ready();
574 }
575 jobs.splice( j, 1 );
576 j--;
577 }
578 }
579 // Execute modules who's dependencies have just been met
580 for ( var r in registry ) {
581 if ( registry[r].state === 'loaded' ) {
582 if ( compare(
583 filter( ['ready'], registry[r].dependencies ),
584 registry[r].dependencies ) )
585 {
586 execute( r );
587 }
588 }
589 }
590 } catch ( e ) {
591 // Run error callbacks of jobs affected by this condition
592 for ( var j = 0; j < jobs.length; j++ ) {
593 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
594 if ( $.isFunction( jobs[j].error ) ) {
595 jobs[j].error();
596 }
597 jobs.splice( j, 1 );
598 j--;
599 }
600 }
601 }
602 }
603
604 /**
605 * Adds a dependencies to the queue with optional callbacks to be run
606 * when the dependencies are ready or fail
607 *
608 * @param dependencies string module name or array of string module names
609 * @param ready function callback to execute when all dependencies are ready
610 * @param error function callback to execute when any dependency fails
611 */
612 function request( dependencies, ready, error ) {
613 // Allow calling by single module name
614 if ( typeof dependencies === 'string' ) {
615 dependencies = [dependencies];
616 if ( dependencies[0] in registry ) {
617 for ( var n = 0; n < registry[dependencies[0]].dependencies.length; n++ ) {
618 dependencies[dependencies.length] = registry[dependencies[0]].dependencies[n];
619 }
620 }
621 }
622 // Add ready and error callbacks if they were given
623 if ( arguments.length > 1 ) {
624 jobs[jobs.length] = {
625 'dependencies': filter(
626 ['undefined', 'registered', 'loading', 'loaded'],
627 dependencies
628 ),
629 'ready': ready,
630 'error': error
631 };
632 }
633 // Queue up any dependencies that are undefined or registered
634 dependencies = filter( ['undefined', 'registered'], dependencies );
635 for ( var n = 0; n < dependencies.length; n++ ) {
636 if ( $.inArray( dependencies[n], queue ) === -1 ) {
637 queue[queue.length] = dependencies[n];
638 }
639 }
640 // Work the queue
641 mw.loader.work();
642 }
643
644 function sortQuery(o) {
645 var sorted = {}, key, a = [];
646 for ( key in o ) {
647 if ( o.hasOwnProperty( key ) ) {
648 a.push( key );
649 }
650 }
651 a.sort();
652 for ( key = 0; key < a.length; key++ ) {
653 sorted[a[key]] = o[a[key]];
654 }
655 return sorted;
656 }
657
658 /**
659 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
660 * to a query string of the form foo.bar,baz|bar.baz,quux
661 */
662 function buildModulesString( moduleMap ) {
663 var arr = [], p;
664 for ( var prefix in moduleMap ) {
665 p = prefix === '' ? '' : prefix + '.';
666 arr.push( p + moduleMap[prefix].join( ',' ) );
667 }
668 return arr.join( '|' );
669 }
670
671 /**
672 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
673 * depending on whether document-ready has occured yet.
674 *
675 * @param src String: URL to script, will be used as the src attribute in the script tag
676 * @param callback Function: Optional callback which will be run when the script is done
677 */
678 function addScript( src, callback ) {
679 var done = false, script;
680 if ( ready ) {
681 // jQuery's getScript method is NOT better than doing this the old-fassioned way
682 // because jQuery will eval the script's code, and errors will not have sane
683 // line numbers.
684 script = document.createElement( 'script' );
685 script.setAttribute( 'src', src );
686 script.setAttribute( 'type', 'text/javascript' );
687 if ( $.isFunction( callback ) ) {
688 // Attach handlers for all browsers -- this is based on jQuery.getScript
689 script.onload = script.onreadystatechange = function() {
690 if (
691 !done
692 && (
693 !this.readyState
694 || this.readyState === 'loaded'
695 || this.readyState === 'complete'
696 )
697 ) {
698 done = true;
699 callback();
700 // Handle memory leak in IE
701 script.onload = script.onreadystatechange = null;
702 if ( script.parentNode ) {
703 script.parentNode.removeChild( script );
704 }
705 }
706 };
707 }
708 document.body.appendChild( script );
709 } else {
710 document.write( mw.html.element(
711 'script', { 'type': 'text/javascript', 'src': src }, ''
712 ) );
713 if ( $.isFunction( callback ) ) {
714 // Document.write is synchronous, so this is called when it's done
715 callback();
716 }
717 }
718 }
719
720 /* Public Methods */
721
722 /**
723 * Requests dependencies from server, loading and executing when things when ready.
724 */
725 this.work = function() {
726 // Build a list of request parameters
727 var base = {
728 'skin': mw.config.get( 'skin' ),
729 'lang': mw.config.get( 'wgUserLanguage' ),
730 'debug': mw.config.get( 'debug' )
731 },
732 // Extend request parameters with a list of modules in the batch
733 requests = [],
734 // Split into groups
735 groups = {};
736
737 // Appends a list of modules to the batch
738 for ( var q = 0; q < queue.length; q++ ) {
739 // Only request modules which are undefined or registered
740 if ( !( queue[q] in registry ) || registry[queue[q]].state === 'registered' ) {
741 // Prevent duplicate entries
742 if ( $.inArray( queue[q], batch ) === -1 ) {
743 batch[batch.length] = queue[q];
744 // Mark registered modules as loading
745 if ( queue[q] in registry ) {
746 registry[queue[q]].state = 'loading';
747 }
748 }
749 }
750 }
751 // Early exit if there's nothing to load
752 if ( !batch.length ) {
753 return;
754 }
755 // Clean up the queue
756 queue = [];
757 // Always order modules alphabetically to help reduce cache
758 // misses for otherwise identical content
759 batch.sort();
760 for ( var b = 0; b < batch.length; b++ ) {
761 var bGroup = registry[batch[b]].group;
762 if ( !( bGroup in groups ) ) {
763 groups[bGroup] = [];
764 }
765 groups[bGroup][groups[bGroup].length] = batch[b];
766 }
767 for ( var group in groups ) {
768 // Calculate the highest timestamp
769 var version = 0;
770 for ( var g = 0; g < groups[group].length; g++ ) {
771 if ( registry[groups[group][g]].version > version ) {
772 version = registry[groups[group][g]].version;
773 }
774 }
775
776 var reqBase = $.extend( { 'version': formatVersionNumber( version ) }, base ),
777 reqBaseLength = $.param( reqBase ).length,
778 reqs = [],
779 limit = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 ),
780 // We may need to split up the request to honor the query string length limit,
781 // so build it piece by piece.
782 l = reqBaseLength + 9, // '&modules='.length == 9
783 r = 0;
784
785 reqs[0] = {}; // { prefix: [ suffixes ] }
786
787 for ( var i = 0; i < groups[group].length; i++ ) {
788 // Determine how many bytes this module would add to the query string
789 var lastDotIndex = groups[group][i].lastIndexOf( '.' ),
790 // Note that these substr() calls work even if lastDotIndex == -1
791 prefix = groups[group][i].substr( 0, lastDotIndex ),
792 suffix = groups[group][i].substr( lastDotIndex + 1 ),
793 bytesAdded = prefix in reqs[r]
794 ? suffix.length + 3 // '%2C'.length == 3
795 : groups[group][i].length + 3; // '%7C'.length == 3
796
797 // If the request would become too long, create a new one,
798 // but don't create empty requests
799 if ( limit > 0 && !$.isEmptyObject( reqs[r] ) && l + bytesAdded > limit ) {
800 // This request would become too long, create a new one
801 r++;
802 reqs[r] = {};
803 l = reqBaseLength + 9;
804 }
805 if ( !( prefix in reqs[r] ) ) {
806 reqs[r][prefix] = [];
807 }
808 reqs[r][prefix].push( suffix );
809 l += bytesAdded;
810 }
811 for ( var r = 0; r < reqs.length; r++ ) {
812 requests[requests.length] = $.extend(
813 { 'modules': buildModulesString( reqs[r] ) }, reqBase
814 );
815 }
816 }
817 // Clear the batch - this MUST happen before we append the
818 // script element to the body or it's possible that the script
819 // will be locally cached, instantly load, and work the batch
820 // again, all before we've cleared it causing each request to
821 // include modules which are already loaded
822 batch = [];
823 // Asynchronously append a script tag to the end of the body
824 for ( var r = 0; r < requests.length; r++ ) {
825 requests[r] = sortQuery( requests[r] );
826 // Append &* to avoid triggering the IE6 extension check
827 var src = mw.config.get( 'wgLoadScript' ) + '?' + $.param( requests[r] ) + '&*';
828 addScript( src );
829 }
830 };
831
832 /**
833 * Registers a module, letting the system know about it and its
834 * dependencies. loader.js files contain calls to this function.
835 */
836 this.register = function( module, version, dependencies, group ) {
837 // Allow multiple registration
838 if ( typeof module === 'object' ) {
839 for ( var m = 0; m < module.length; m++ ) {
840 if ( typeof module[m] === 'string' ) {
841 mw.loader.register( module[m] );
842 } else if ( typeof module[m] === 'object' ) {
843 mw.loader.register.apply( mw.loader, module[m] );
844 }
845 }
846 return;
847 }
848 // Validate input
849 if ( typeof module !== 'string' ) {
850 throw new Error( 'module must be a string, not a ' + typeof module );
851 }
852 if ( registry[module] !== undefined ) {
853 throw new Error( 'module already implemented: ' + module );
854 }
855 // List the module as registered
856 registry[module] = {
857 'state': 'registered',
858 'group': typeof group === 'string' ? group : null,
859 'dependencies': [],
860 'version': version !== undefined ? parseInt( version, 10 ) : 0
861 };
862 if ( typeof dependencies === 'string' ) {
863 // Allow dependencies to be given as a single module name
864 registry[module].dependencies = [dependencies];
865 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
866 // Allow dependencies to be given as an array of module names
867 // or a function which returns an array
868 registry[module].dependencies = dependencies;
869 }
870 };
871
872 /**
873 * Implements a module, giving the system a course of action to take
874 * upon loading. Results of a request for one or more modules contain
875 * calls to this function.
876 *
877 * All arguments are required.
878 *
879 * @param module String: Name of module
880 * @param script Mixed: Function of module code or String of URL to be used as the src
881 * attribute when adding a script element to the body
882 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
883 * keyed by media-type
884 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
885 */
886 this.implement = function( module, script, style, msgs ) {
887 // Validate input
888 if ( typeof module !== 'string' ) {
889 throw new Error( 'module must be a string, not a ' + typeof module );
890 }
891 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
892 throw new Error( 'script must be a function or an array, not a ' + typeof script );
893 }
894 if ( !$.isPlainObject( style ) ) {
895 throw new Error( 'style must be an object, not a ' + typeof style );
896 }
897 if ( !$.isPlainObject( msgs ) ) {
898 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
899 }
900 // Automatically register module
901 if ( registry[module] === undefined ) {
902 mw.loader.register( module );
903 }
904 // Check for duplicate implementation
905 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
906 throw new Error( 'module already implemeneted: ' + module );
907 }
908 // Mark module as loaded
909 registry[module].state = 'loaded';
910 // Attach components
911 registry[module].script = script;
912 registry[module].style = style;
913 registry[module].messages = msgs;
914 // Execute or queue callback
915 if ( compare(
916 filter( ['ready'], registry[module].dependencies ),
917 registry[module].dependencies ) )
918 {
919 execute( module );
920 } else {
921 request( module );
922 }
923 };
924
925 /**
926 * Executes a function as soon as one or more required modules are ready
927 *
928 * @param dependencies string or array of strings of modules names the callback
929 * dependencies to be ready before executing
930 * @param ready function callback to execute when all dependencies are ready (optional)
931 * @param error function callback to execute when if dependencies have a errors (optional)
932 */
933 this.using = function( dependencies, ready, error ) {
934 var tod = typeof dependencies;
935 // Validate input
936 if ( tod !== 'object' && tod !== 'string' ) {
937 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
938 }
939 // Allow calling with a single dependency as a string
940 if ( tod === 'string' ) {
941 dependencies = [dependencies];
942 }
943 // Resolve entire dependency map
944 dependencies = resolve( dependencies );
945 // If all dependencies are met, execute ready immediately
946 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
947 if ( $.isFunction( ready ) ) {
948 ready();
949 }
950 }
951 // If any dependencies have errors execute error immediately
952 else if ( filter( ['error'], dependencies ).length ) {
953 if ( $.isFunction( error ) ) {
954 error();
955 }
956 }
957 // Since some dependencies are not yet ready, queue up a request
958 else {
959 request( dependencies, ready, error );
960 }
961 };
962
963 /**
964 * Loads an external script or one or more modules for future use
965 *
966 * @param modules mixed either the name of a module, array of modules,
967 * or a URL of an external script or style
968 * @param type string mime-type to use if calling with a URL of an
969 * external script or style; acceptable values are "text/css" and
970 * "text/javascript"; if no type is provided, text/javascript is assumed.
971 */
972 this.load = function( modules, type ) {
973 // Validate input
974 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
975 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
976 }
977 // Allow calling with an external script or single dependency as a string
978 if ( typeof modules === 'string' ) {
979 // Support adding arbitrary external scripts
980 if ( modules.substr( 0, 7 ) === 'http://' || modules.substr( 0, 8 ) === 'https://' ) {
981 if ( type === 'text/css' ) {
982 $( 'head' ).append( $( '<link/>', {
983 rel: 'stylesheet',
984 type: 'text/css',
985 href: modules
986 } ) );
987 return true;
988 } else if ( type === 'text/javascript' || type === undefined ) {
989 addScript( modules );
990 return true;
991 }
992 // Unknown type
993 return false;
994 }
995 // Called with single module
996 modules = [modules];
997 }
998 // Resolve entire dependency map
999 modules = resolve( modules );
1000 // If all modules are ready, nothing dependency be done
1001 if ( compare( filter( ['ready'], modules ), modules ) ) {
1002 return true;
1003 }
1004 // If any modules have errors return false
1005 else if ( filter( ['error'], modules ).length ) {
1006 return false;
1007 }
1008 // Since some modules are not yet ready, queue up a request
1009 else {
1010 request( modules );
1011 return true;
1012 }
1013 };
1014
1015 /**
1016 * Changes the state of a module
1017 *
1018 * @param module string module name or object of module name/state pairs
1019 * @param state string state name
1020 */
1021 this.state = function( module, state ) {
1022 if ( typeof module === 'object' ) {
1023 for ( var m in module ) {
1024 mw.loader.state( m, module[m] );
1025 }
1026 return;
1027 }
1028 if ( !( module in registry ) ) {
1029 mw.loader.register( module );
1030 }
1031 registry[module].state = state;
1032 };
1033
1034 /**
1035 * Gets the version of a module
1036 *
1037 * @param module string name of module to get version for
1038 */
1039 this.getVersion = function( module ) {
1040 if ( module in registry && 'version' in registry[module] ) {
1041 return formatVersionNumber( registry[module].version );
1042 }
1043 return null;
1044 };
1045
1046 /**
1047 * @deprecated use mw.loader.getVersion() instead
1048 */
1049 this.version = function() {
1050 return mw.loader.getVersion.apply( mw.loader, arguments );
1051 };
1052
1053 /**
1054 * Gets the state of a module
1055 *
1056 * @param module string name of module to get state for
1057 */
1058 this.getState = function( module ) {
1059 if ( module in registry && 'state' in registry[module] ) {
1060 return registry[module].state;
1061 }
1062 return null;
1063 };
1064
1065 /* Cache document ready status */
1066
1067 $(document).ready( function() { ready = true; } );
1068 } )();
1069
1070 /** HTML construction helper functions */
1071 this.html = new ( function () {
1072 var escapeCallback = function( s ) {
1073 switch ( s ) {
1074 case "'":
1075 return '&#039;';
1076 case '"':
1077 return '&quot;';
1078 case '<':
1079 return '&lt;';
1080 case '>':
1081 return '&gt;';
1082 case '&':
1083 return '&amp;';
1084 }
1085 };
1086
1087 /**
1088 * Escape a string for HTML. Converts special characters to HTML entities.
1089 * @param s The string to escape
1090 */
1091 this.escape = function( s ) {
1092 return s.replace( /['"<>&]/g, escapeCallback );
1093 };
1094
1095 /**
1096 * Wrapper object for raw HTML passed to mw.html.element().
1097 */
1098 this.Raw = function( value ) {
1099 this.value = value;
1100 };
1101
1102 /**
1103 * Wrapper object for CDATA element contents passed to mw.html.element()
1104 */
1105 this.Cdata = function( value ) {
1106 this.value = value;
1107 };
1108
1109 /**
1110 * Create an HTML element string, with safe escaping.
1111 *
1112 * @param name The tag name.
1113 * @param attrs An object with members mapping element names to values
1114 * @param contents The contents of the element. May be either:
1115 * - string: The string is escaped.
1116 * - null or undefined: The short closing form is used, e.g. <br/>.
1117 * - this.Raw: The value attribute is included without escaping.
1118 * - this.Cdata: The value attribute is included, and an exception is
1119 * thrown if it contains an illegal ETAGO delimiter.
1120 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1121 *
1122 * Example:
1123 * var h = mw.html;
1124 * return h.element( 'div', {},
1125 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1126 * Returns <div><img src="&lt;"/></div>
1127 */
1128 this.element = function( name, attrs, contents ) {
1129 var s = '<' + name;
1130 for ( var attrName in attrs ) {
1131 s += ' ' + attrName + '="' + this.escape( attrs[attrName] ) + '"';
1132 }
1133 if ( contents === undefined || contents === null ) {
1134 // Self close tag
1135 s += '/>';
1136 return s;
1137 }
1138 // Regular open tag
1139 s += '>';
1140 if ( typeof contents === 'string' ) {
1141 // Escaped
1142 s += this.escape( contents );
1143 } else if ( contents instanceof this.Raw ) {
1144 // Raw HTML inclusion
1145 s += contents.value;
1146 } else if ( contents instanceof this.Cdata ) {
1147 // CDATA
1148 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1149 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1150 }
1151 s += contents.value;
1152 } else {
1153 throw new Error( 'mw.html.element: Invalid type of contents' );
1154 }
1155 s += '</' + name + '>';
1156 return s;
1157 };
1158 } )();
1159
1160 /* Extension points */
1161
1162 this.legacy = {};
1163
1164 } )( jQuery );
1165
1166 // Alias $j to jQuery for backwards compatibility
1167 window.$j = jQuery;
1168
1169 // Auto-register from pre-loaded startup scripts
1170 if ( jQuery.isFunction( startUp ) ) {
1171 startUp();
1172 delete startUp;
1173 }