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