More mediawiki.js cleanup (addScript AJAX)
[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.ajax
689 script.onload = script.onreadystatechange = function() {
690
691 if (
692 !done
693 && (
694 !script.readyState
695 || /loaded|complete/.test( script.readyState )
696 )
697 ) {
698
699 done = true;
700
701 // Handle memory leak in IE
702 script.onload = script.onreadystatechange = null;
703
704 callback();
705
706 if ( script.parentNode ) {
707 script.parentNode.removeChild( script );
708 }
709
710 // Dereference the script
711 script = undefined;
712 }
713 };
714 }
715 document.body.appendChild( script );
716 } else {
717 document.write( mw.html.element(
718 'script', { 'type': 'text/javascript', 'src': src }, ''
719 ) );
720 if ( $.isFunction( callback ) ) {
721 // Document.write is synchronous, so this is called when it's done
722 callback();
723 }
724 }
725 }
726
727 /* Public Methods */
728
729 /**
730 * Requests dependencies from server, loading and executing when things when ready.
731 */
732 this.work = function() {
733 // Build a list of request parameters
734 var base = {
735 'skin': mw.config.get( 'skin' ),
736 'lang': mw.config.get( 'wgUserLanguage' ),
737 'debug': mw.config.get( 'debug' )
738 },
739 // Extend request parameters with a list of modules in the batch
740 requests = [],
741 // Split into groups
742 groups = {};
743
744 // Appends a list of modules to the batch
745 for ( var q = 0; q < queue.length; q++ ) {
746 // Only request modules which are undefined or registered
747 if ( !( queue[q] in registry ) || registry[queue[q]].state === 'registered' ) {
748 // Prevent duplicate entries
749 if ( $.inArray( queue[q], batch ) === -1 ) {
750 batch[batch.length] = queue[q];
751 // Mark registered modules as loading
752 if ( queue[q] in registry ) {
753 registry[queue[q]].state = 'loading';
754 }
755 }
756 }
757 }
758 // Early exit if there's nothing to load
759 if ( !batch.length ) {
760 return;
761 }
762 // Clean up the queue
763 queue = [];
764 // Always order modules alphabetically to help reduce cache
765 // misses for otherwise identical content
766 batch.sort();
767 for ( var b = 0; b < batch.length; b++ ) {
768 var bGroup = registry[batch[b]].group;
769 if ( !( bGroup in groups ) ) {
770 groups[bGroup] = [];
771 }
772 groups[bGroup][groups[bGroup].length] = batch[b];
773 }
774 for ( var group in groups ) {
775 // Calculate the highest timestamp
776 var version = 0;
777 for ( var g = 0; g < groups[group].length; g++ ) {
778 if ( registry[groups[group][g]].version > version ) {
779 version = registry[groups[group][g]].version;
780 }
781 }
782
783 var reqBase = $.extend( { 'version': formatVersionNumber( version ) }, base ),
784 reqBaseLength = $.param( reqBase ).length,
785 reqs = [],
786 limit = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 ),
787 // We may need to split up the request to honor the query string length limit,
788 // so build it piece by piece.
789 l = reqBaseLength + 9, // '&modules='.length == 9
790 r = 0;
791
792 reqs[0] = {}; // { prefix: [ suffixes ] }
793
794 for ( var i = 0; i < groups[group].length; i++ ) {
795 // Determine how many bytes this module would add to the query string
796 var lastDotIndex = groups[group][i].lastIndexOf( '.' ),
797 // Note that these substr() calls work even if lastDotIndex == -1
798 prefix = groups[group][i].substr( 0, lastDotIndex ),
799 suffix = groups[group][i].substr( lastDotIndex + 1 ),
800 bytesAdded = prefix in reqs[r]
801 ? suffix.length + 3 // '%2C'.length == 3
802 : groups[group][i].length + 3; // '%7C'.length == 3
803
804 // If the request would become too long, create a new one,
805 // but don't create empty requests
806 if ( limit > 0 && !$.isEmptyObject( reqs[r] ) && l + bytesAdded > limit ) {
807 // This request would become too long, create a new one
808 r++;
809 reqs[r] = {};
810 l = reqBaseLength + 9;
811 }
812 if ( !( prefix in reqs[r] ) ) {
813 reqs[r][prefix] = [];
814 }
815 reqs[r][prefix].push( suffix );
816 l += bytesAdded;
817 }
818 for ( var r = 0; r < reqs.length; r++ ) {
819 requests[requests.length] = $.extend(
820 { 'modules': buildModulesString( reqs[r] ) }, reqBase
821 );
822 }
823 }
824 // Clear the batch - this MUST happen before we append the
825 // script element to the body or it's possible that the script
826 // will be locally cached, instantly load, and work the batch
827 // again, all before we've cleared it causing each request to
828 // include modules which are already loaded
829 batch = [];
830 // Asynchronously append a script tag to the end of the body
831 for ( var r = 0; r < requests.length; r++ ) {
832 requests[r] = sortQuery( requests[r] );
833 // Append &* to avoid triggering the IE6 extension check
834 var src = mw.config.get( 'wgLoadScript' ) + '?' + $.param( requests[r] ) + '&*';
835 addScript( src );
836 }
837 };
838
839 /**
840 * Registers a module, letting the system know about it and its
841 * dependencies. loader.js files contain calls to this function.
842 */
843 this.register = function( module, version, dependencies, group ) {
844 // Allow multiple registration
845 if ( typeof module === 'object' ) {
846 for ( var m = 0; m < module.length; m++ ) {
847 if ( typeof module[m] === 'string' ) {
848 mw.loader.register( module[m] );
849 } else if ( typeof module[m] === 'object' ) {
850 mw.loader.register.apply( mw.loader, module[m] );
851 }
852 }
853 return;
854 }
855 // Validate input
856 if ( typeof module !== 'string' ) {
857 throw new Error( 'module must be a string, not a ' + typeof module );
858 }
859 if ( registry[module] !== undefined ) {
860 throw new Error( 'module already implemented: ' + module );
861 }
862 // List the module as registered
863 registry[module] = {
864 'state': 'registered',
865 'group': typeof group === 'string' ? group : null,
866 'dependencies': [],
867 'version': version !== undefined ? parseInt( version, 10 ) : 0
868 };
869 if ( typeof dependencies === 'string' ) {
870 // Allow dependencies to be given as a single module name
871 registry[module].dependencies = [dependencies];
872 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
873 // Allow dependencies to be given as an array of module names
874 // or a function which returns an array
875 registry[module].dependencies = dependencies;
876 }
877 };
878
879 /**
880 * Implements a module, giving the system a course of action to take
881 * upon loading. Results of a request for one or more modules contain
882 * calls to this function.
883 *
884 * All arguments are required.
885 *
886 * @param module String: Name of module
887 * @param script Mixed: Function of module code or String of URL to be used as the src
888 * attribute when adding a script element to the body
889 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
890 * keyed by media-type
891 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
892 */
893 this.implement = function( module, script, style, msgs ) {
894 // Validate input
895 if ( typeof module !== 'string' ) {
896 throw new Error( 'module must be a string, not a ' + typeof module );
897 }
898 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
899 throw new Error( 'script must be a function or an array, not a ' + typeof script );
900 }
901 if ( !$.isPlainObject( style ) ) {
902 throw new Error( 'style must be an object, not a ' + typeof style );
903 }
904 if ( !$.isPlainObject( msgs ) ) {
905 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
906 }
907 // Automatically register module
908 if ( registry[module] === undefined ) {
909 mw.loader.register( module );
910 }
911 // Check for duplicate implementation
912 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
913 throw new Error( 'module already implemeneted: ' + module );
914 }
915 // Mark module as loaded
916 registry[module].state = 'loaded';
917 // Attach components
918 registry[module].script = script;
919 registry[module].style = style;
920 registry[module].messages = msgs;
921 // Execute or queue callback
922 if ( compare(
923 filter( ['ready'], registry[module].dependencies ),
924 registry[module].dependencies ) )
925 {
926 execute( module );
927 } else {
928 request( module );
929 }
930 };
931
932 /**
933 * Executes a function as soon as one or more required modules are ready
934 *
935 * @param dependencies string or array of strings of modules names the callback
936 * dependencies to be ready before executing
937 * @param ready function callback to execute when all dependencies are ready (optional)
938 * @param error function callback to execute when if dependencies have a errors (optional)
939 */
940 this.using = function( dependencies, ready, error ) {
941 var tod = typeof dependencies;
942 // Validate input
943 if ( tod !== 'object' && tod !== 'string' ) {
944 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
945 }
946 // Allow calling with a single dependency as a string
947 if ( tod === 'string' ) {
948 dependencies = [dependencies];
949 }
950 // Resolve entire dependency map
951 dependencies = resolve( dependencies );
952 // If all dependencies are met, execute ready immediately
953 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
954 if ( $.isFunction( ready ) ) {
955 ready();
956 }
957 }
958 // If any dependencies have errors execute error immediately
959 else if ( filter( ['error'], dependencies ).length ) {
960 if ( $.isFunction( error ) ) {
961 error();
962 }
963 }
964 // Since some dependencies are not yet ready, queue up a request
965 else {
966 request( dependencies, ready, error );
967 }
968 };
969
970 /**
971 * Loads an external script or one or more modules for future use
972 *
973 * @param modules mixed either the name of a module, array of modules,
974 * or a URL of an external script or style
975 * @param type string mime-type to use if calling with a URL of an
976 * external script or style; acceptable values are "text/css" and
977 * "text/javascript"; if no type is provided, text/javascript is assumed.
978 */
979 this.load = function( modules, type ) {
980 // Validate input
981 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
982 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
983 }
984 // Allow calling with an external script or single dependency as a string
985 if ( typeof modules === 'string' ) {
986 // Support adding arbitrary external scripts
987 if ( modules.substr( 0, 7 ) === 'http://' || modules.substr( 0, 8 ) === 'https://' ) {
988 if ( type === 'text/css' ) {
989 $( 'head' ).append( $( '<link/>', {
990 rel: 'stylesheet',
991 type: 'text/css',
992 href: modules
993 } ) );
994 return true;
995 } else if ( type === 'text/javascript' || type === undefined ) {
996 addScript( modules );
997 return true;
998 }
999 // Unknown type
1000 return false;
1001 }
1002 // Called with single module
1003 modules = [modules];
1004 }
1005 // Resolve entire dependency map
1006 modules = resolve( modules );
1007 // If all modules are ready, nothing dependency be done
1008 if ( compare( filter( ['ready'], modules ), modules ) ) {
1009 return true;
1010 }
1011 // If any modules have errors return false
1012 else if ( filter( ['error'], modules ).length ) {
1013 return false;
1014 }
1015 // Since some modules are not yet ready, queue up a request
1016 else {
1017 request( modules );
1018 return true;
1019 }
1020 };
1021
1022 /**
1023 * Changes the state of a module
1024 *
1025 * @param module string module name or object of module name/state pairs
1026 * @param state string state name
1027 */
1028 this.state = function( module, state ) {
1029 if ( typeof module === 'object' ) {
1030 for ( var m in module ) {
1031 mw.loader.state( m, module[m] );
1032 }
1033 return;
1034 }
1035 if ( !( module in registry ) ) {
1036 mw.loader.register( module );
1037 }
1038 registry[module].state = state;
1039 };
1040
1041 /**
1042 * Gets the version of a module
1043 *
1044 * @param module string name of module to get version for
1045 */
1046 this.getVersion = function( module ) {
1047 if ( module in registry && 'version' in registry[module] ) {
1048 return formatVersionNumber( registry[module].version );
1049 }
1050 return null;
1051 };
1052
1053 /**
1054 * @deprecated use mw.loader.getVersion() instead
1055 */
1056 this.version = function() {
1057 return mw.loader.getVersion.apply( mw.loader, arguments );
1058 };
1059
1060 /**
1061 * Gets the state of a module
1062 *
1063 * @param module string name of module to get state for
1064 */
1065 this.getState = function( module ) {
1066 if ( module in registry && 'state' in registry[module] ) {
1067 return registry[module].state;
1068 }
1069 return null;
1070 };
1071
1072 /* Cache document ready status */
1073
1074 $(document).ready( function() { ready = true; } );
1075 } )();
1076
1077 /** HTML construction helper functions */
1078 this.html = new ( function () {
1079 var escapeCallback = function( s ) {
1080 switch ( s ) {
1081 case "'":
1082 return '&#039;';
1083 case '"':
1084 return '&quot;';
1085 case '<':
1086 return '&lt;';
1087 case '>':
1088 return '&gt;';
1089 case '&':
1090 return '&amp;';
1091 }
1092 };
1093
1094 /**
1095 * Escape a string for HTML. Converts special characters to HTML entities.
1096 * @param s The string to escape
1097 */
1098 this.escape = function( s ) {
1099 return s.replace( /['"<>&]/g, escapeCallback );
1100 };
1101
1102 /**
1103 * Wrapper object for raw HTML passed to mw.html.element().
1104 */
1105 this.Raw = function( value ) {
1106 this.value = value;
1107 };
1108
1109 /**
1110 * Wrapper object for CDATA element contents passed to mw.html.element()
1111 */
1112 this.Cdata = function( value ) {
1113 this.value = value;
1114 };
1115
1116 /**
1117 * Create an HTML element string, with safe escaping.
1118 *
1119 * @param name The tag name.
1120 * @param attrs An object with members mapping element names to values
1121 * @param contents The contents of the element. May be either:
1122 * - string: The string is escaped.
1123 * - null or undefined: The short closing form is used, e.g. <br/>.
1124 * - this.Raw: The value attribute is included without escaping.
1125 * - this.Cdata: The value attribute is included, and an exception is
1126 * thrown if it contains an illegal ETAGO delimiter.
1127 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1128 *
1129 * Example:
1130 * var h = mw.html;
1131 * return h.element( 'div', {},
1132 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1133 * Returns <div><img src="&lt;"/></div>
1134 */
1135 this.element = function( name, attrs, contents ) {
1136 var s = '<' + name;
1137 for ( var attrName in attrs ) {
1138 s += ' ' + attrName + '="' + this.escape( attrs[attrName] ) + '"';
1139 }
1140 if ( contents === undefined || contents === null ) {
1141 // Self close tag
1142 s += '/>';
1143 return s;
1144 }
1145 // Regular open tag
1146 s += '>';
1147 if ( typeof contents === 'string' ) {
1148 // Escaped
1149 s += this.escape( contents );
1150 } else if ( contents instanceof this.Raw ) {
1151 // Raw HTML inclusion
1152 s += contents.value;
1153 } else if ( contents instanceof this.Cdata ) {
1154 // CDATA
1155 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1156 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1157 }
1158 s += contents.value;
1159 } else {
1160 throw new Error( 'mw.html.element: Invalid type of contents' );
1161 }
1162 s += '</' + name + '>';
1163 return s;
1164 };
1165 } )();
1166
1167 /* Extension points */
1168
1169 this.legacy = {};
1170
1171 } )( jQuery );
1172
1173 // Alias $j to jQuery for backwards compatibility
1174 window.$j = jQuery;
1175
1176 // Auto-register from pre-loaded startup scripts
1177 if ( jQuery.isFunction( startUp ) ) {
1178 startUp();
1179 delete startUp;
1180 }