Follows-up r93515 CR: Whitespace
[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 * For exact details on support for script, style and messages, look at
303 * mw.loader.implement.
304 *
305 * Format:
306 * {
307 * 'moduleName': {
308 * 'version': ############## (unix timestamp),
309 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
310 * 'group': 'somegroup', (or) null,
311 * 'source': 'local', 'someforeignwiki', (or) null
312 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
313 * 'script': ...,
314 * 'style': ...,
315 * 'messages': { 'key': 'value' },
316 * }
317 * }
318 */
319 var registry = {},
320 /**
321 * Mapping of sources, keyed by source-id, values are objects.
322 * Format:
323 * {
324 * 'sourceId': {
325 * 'loadScript': 'http://foo.bar/w/load.php'
326 * }
327 * }
328 */
329 sources = {},
330 // List of modules which will be loaded as when ready
331 batch = [],
332 // List of modules to be loaded
333 queue = [],
334 // List of callback functions waiting for modules to be ready to be called
335 jobs = [],
336 // Flag inidicating that document ready has occured
337 ready = false,
338 // Selector cache for the marker element. Use getMarker() to get/use the marker!
339 $marker = null;
340
341 /* Private Methods */
342
343 function getMarker(){
344 // Cached ?
345 if ( $marker ) {
346 return $marker;
347 } else {
348 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
349 if ( $marker.length ) {
350 return $marker;
351 }
352 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
353 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
354 return $marker;
355 }
356 }
357
358 function compare( a, b ) {
359 if ( a.length !== b.length ) {
360 return false;
361 }
362 for ( var i = 0; i < b.length; i++ ) {
363 if ( $.isArray( a[i] ) ) {
364 if ( !compare( a[i], b[i] ) ) {
365 return false;
366 }
367 }
368 if ( a[i] !== b[i] ) {
369 return false;
370 }
371 }
372 return true;
373 }
374
375 /**
376 * Generates an ISO8601 "basic" string from a UNIX timestamp
377 */
378 function formatVersionNumber( timestamp ) {
379 var pad = function( a, b, c ) {
380 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
381 },
382 d = new Date();
383 d.setTime( timestamp * 1000 );
384 return [
385 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
386 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
387 ].join( '' );
388 }
389
390 /**
391 * Recursively resolves dependencies and detects circular references
392 */
393 function recurse( module, resolved, unresolved ) {
394 if ( registry[module] === undefined ) {
395 throw new Error( 'Unknown dependency: ' + module );
396 }
397 // Resolves dynamic loader function and replaces it with its own results
398 if ( $.isFunction( registry[module].dependencies ) ) {
399 registry[module].dependencies = registry[module].dependencies();
400 // Ensures the module's dependencies are always in an array
401 if ( typeof registry[module].dependencies !== 'object' ) {
402 registry[module].dependencies = [registry[module].dependencies];
403 }
404 }
405 // Tracks down dependencies
406 for ( var n = 0; n < registry[module].dependencies.length; n++ ) {
407 if ( $.inArray( registry[module].dependencies[n], resolved ) === -1 ) {
408 if ( $.inArray( registry[module].dependencies[n], unresolved ) !== -1 ) {
409 throw new Error(
410 'Circular reference detected: ' + module +
411 ' -> ' + registry[module].dependencies[n]
412 );
413 }
414 recurse( registry[module].dependencies[n], resolved, unresolved );
415 }
416 }
417 resolved[resolved.length] = module;
418 unresolved.splice( $.inArray( module, unresolved ), 1 );
419 }
420
421 /**
422 * Gets a list of module names that a module depends on in their proper dependency order
423 *
424 * @param module string module name or array of string module names
425 * @return list of dependencies
426 * @throws Error if circular reference is detected
427 */
428 function resolve( module ) {
429 // Allow calling with an array of module names
430 if ( typeof module === 'object' ) {
431 var modules = [];
432 for ( var m = 0; m < module.length; m++ ) {
433 var dependencies = resolve( module[m] );
434 for ( var n = 0; n < dependencies.length; n++ ) {
435 modules[modules.length] = dependencies[n];
436 }
437 }
438 return modules;
439 } else if ( typeof module === 'string' ) {
440 // Undefined modules have no dependencies
441 if ( !( module in registry ) ) {
442 return [];
443 }
444 var resolved = [];
445 recurse( module, resolved, [] );
446 return resolved;
447 }
448 throw new Error( 'Invalid module argument: ' + module );
449 }
450
451 /**
452 * Narrows a list of module names down to those matching a specific
453 * state. Possible states are 'undefined', 'registered', 'loading',
454 * 'loaded', or 'ready'
455 *
456 * @param states string or array of strings of module states to filter by
457 * @param modules array list of module names to filter (optional, all modules
458 * will be used by default)
459 * @return array list of filtered module names
460 */
461 function filter( states, modules ) {
462 // Allow states to be given as a string
463 if ( typeof states === 'string' ) {
464 states = [states];
465 }
466 // If called without a list of modules, build and use a list of all modules
467 var list = [], module;
468 if ( modules === undefined ) {
469 modules = [];
470 for ( module in registry ) {
471 modules[modules.length] = module;
472 }
473 }
474 // Build a list of modules which are in one of the specified states
475 for ( var s = 0; s < states.length; s++ ) {
476 for ( var m = 0; m < modules.length; m++ ) {
477 if ( registry[modules[m]] === undefined ) {
478 // Module does not exist
479 if ( states[s] === 'undefined' ) {
480 // OK, undefined
481 list[list.length] = modules[m];
482 }
483 } else {
484 // Module exists, check state
485 if ( registry[modules[m]].state === states[s] ) {
486 // OK, correct state
487 list[list.length] = modules[m];
488 }
489 }
490 }
491 }
492 return list;
493 }
494
495 /**
496 * Executes a loaded module, making it ready to use
497 *
498 * @param module string module name to execute
499 */
500 function execute( module, callback ) {
501 if ( registry[module] === undefined ) {
502 throw new Error( 'Module has not been registered yet: ' + module );
503 } else if ( registry[module].state === 'registered' ) {
504 throw new Error( 'Module has not been requested from the server yet: ' + module );
505 } else if ( registry[module].state === 'loading' ) {
506 throw new Error( 'Module has not completed loading yet: ' + module );
507 } else if ( registry[module].state === 'ready' ) {
508 throw new Error( 'Module has already been loaded: ' + module );
509 }
510 // Add styles
511 var style;
512 if ( $.isPlainObject( registry[module].style ) ) {
513 for ( var media in registry[module].style ) {
514 style = registry[module].style[media];
515 if ( $.isArray( style ) ) {
516 for ( var i = 0; i < style.length; i++ ) {
517 getMarker().before( mw.html.element( 'link', {
518 'type': 'text/css',
519 'rel': 'stylesheet',
520 'href': style[i]
521 } ) );
522 }
523 } else if ( typeof style === 'string' ) {
524 getMarker().before( mw.html.element( 'style', {
525 'type': 'text/css',
526 'media': media
527 }, new mw.html.Cdata( style ) ) );
528 }
529 }
530 }
531 // Add localizations to message system
532 if ( $.isPlainObject( registry[module].messages ) ) {
533 mw.messages.set( registry[module].messages );
534 }
535 // Execute script
536 try {
537 var script = registry[module].script,
538 markModuleReady = function() {
539 registry[module].state = 'ready';
540 handlePending( module );
541 if ( $.isFunction( callback ) ) {
542 callback();
543 }
544 };
545
546 if ( $.isArray( script ) ) {
547 var done = 0;
548 if ( script.length === 0 ) {
549 // No scripts in this module? Let's dive out early.
550 markModuleReady();
551 }
552 for ( var i = 0; i < script.length; i++ ) {
553 registry[module].state = 'loading';
554 addScript( script[i], function() {
555 if ( ++done === script.length ) {
556 markModuleReady();
557 }
558 } );
559 }
560 } else if ( $.isFunction( script ) ) {
561 script( jQuery );
562 markModuleReady();
563 }
564 } catch ( e ) {
565 // This needs to NOT use mw.log because these errors are common in production mode
566 // and not in debug mode, such as when a symbol that should be global isn't exported
567 if ( window.console && typeof window.console.log === 'function' ) {
568 console.log( 'mw.loader::execute> Exception thrown by ' + module + ': ' + e.message );
569 }
570 registry[module].state = 'error';
571 throw e;
572 }
573 }
574
575 /**
576 * Automatically executes jobs and modules which are pending with satistifed dependencies.
577 *
578 * This is used when dependencies are satisfied, such as when a module is executed.
579 */
580 function handlePending( module ) {
581 try {
582 // Run jobs who's dependencies have just been met
583 for ( var j = 0; j < jobs.length; j++ ) {
584 if ( compare(
585 filter( 'ready', jobs[j].dependencies ),
586 jobs[j].dependencies ) )
587 {
588 if ( $.isFunction( jobs[j].ready ) ) {
589 jobs[j].ready();
590 }
591 jobs.splice( j, 1 );
592 j--;
593 }
594 }
595 // Execute modules who's dependencies have just been met
596 for ( var r in registry ) {
597 if ( registry[r].state === 'loaded' ) {
598 if ( compare(
599 filter( ['ready'], registry[r].dependencies ),
600 registry[r].dependencies ) )
601 {
602 execute( r );
603 }
604 }
605 }
606 } catch ( e ) {
607 // Run error callbacks of jobs affected by this condition
608 for ( var j = 0; j < jobs.length; j++ ) {
609 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
610 if ( $.isFunction( jobs[j].error ) ) {
611 jobs[j].error();
612 }
613 jobs.splice( j, 1 );
614 j--;
615 }
616 }
617 }
618 }
619
620 /**
621 * Adds a dependencies to the queue with optional callbacks to be run
622 * when the dependencies are ready or fail
623 *
624 * @param dependencies string module name or array of string module names
625 * @param ready function callback to execute when all dependencies are ready
626 * @param error function callback to execute when any dependency fails
627 */
628 function request( dependencies, ready, error ) {
629 // Allow calling by single module name
630 if ( typeof dependencies === 'string' ) {
631 dependencies = [dependencies];
632 if ( dependencies[0] in registry ) {
633 // Cache repetitively accessed deep level object member
634 var regItemDeps = registry[dependencies[0]].dependencies,
635 // Cache to avoid looped access to length property
636 regItemDepLen = regItemDeps.length;
637 for ( var n = 0; n < regItemDepLen; n++ ) {
638 dependencies[dependencies.length] = regItemDeps[n];
639 }
640 }
641 }
642 // Add ready and error callbacks if they were given
643 if ( arguments.length > 1 ) {
644 jobs[jobs.length] = {
645 'dependencies': filter(
646 ['undefined', 'registered', 'loading', 'loaded'],
647 dependencies
648 ),
649 'ready': ready,
650 'error': error
651 };
652 }
653 // Queue up any dependencies that are undefined or registered
654 dependencies = filter( ['undefined', 'registered'], dependencies );
655 for ( var n = 0; n < dependencies.length; n++ ) {
656 if ( $.inArray( dependencies[n], queue ) === -1 ) {
657 queue[queue.length] = dependencies[n];
658 }
659 }
660 // Work the queue
661 mw.loader.work();
662 }
663
664 function sortQuery(o) {
665 var sorted = {}, key, a = [];
666 for ( key in o ) {
667 if ( o.hasOwnProperty( key ) ) {
668 a.push( key );
669 }
670 }
671 a.sort();
672 for ( key = 0; key < a.length; key++ ) {
673 sorted[a[key]] = o[a[key]];
674 }
675 return sorted;
676 }
677
678 /**
679 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
680 * to a query string of the form foo.bar,baz|bar.baz,quux
681 */
682 function buildModulesString( moduleMap ) {
683 var arr = [], p;
684 for ( var prefix in moduleMap ) {
685 p = prefix === '' ? '' : prefix + '.';
686 arr.push( p + moduleMap[prefix].join( ',' ) );
687 }
688 return arr.join( '|' );
689 }
690
691 /**
692 * Adds a script tag to the body, either using document.write or low-level DOM manipulation,
693 * depending on whether document-ready has occured yet.
694 *
695 * @param src String: URL to script, will be used as the src attribute in the script tag
696 * @param callback Function: Optional callback which will be run when the script is done
697 */
698 function addScript( src, callback ) {
699 var done = false, script;
700 if ( ready ) {
701 // jQuery's getScript method is NOT better than doing this the old-fassioned way
702 // because jQuery will eval the script's code, and errors will not have sane
703 // line numbers.
704 script = document.createElement( 'script' );
705 script.setAttribute( 'src', src );
706 script.setAttribute( 'type', 'text/javascript' );
707 if ( $.isFunction( callback ) ) {
708 // Attach handlers for all browsers -- this is based on jQuery.ajax
709 script.onload = script.onreadystatechange = function() {
710
711 if (
712 !done
713 && (
714 !script.readyState
715 || /loaded|complete/.test( script.readyState )
716 )
717 ) {
718
719 done = true;
720
721 // Handle memory leak in IE
722 script.onload = script.onreadystatechange = null;
723
724 callback();
725
726 if ( script.parentNode ) {
727 script.parentNode.removeChild( script );
728 }
729
730 // Dereference the script
731 script = undefined;
732 }
733 };
734 }
735 document.body.appendChild( script );
736 } else {
737 document.write( mw.html.element(
738 'script', { 'type': 'text/javascript', 'src': src }, ''
739 ) );
740 if ( $.isFunction( callback ) ) {
741 // Document.write is synchronous, so this is called when it's done
742 callback();
743 }
744 }
745 }
746
747 /**
748 * Asynchronously append a script tag to the end of the body
749 * that invokes load.php
750 * @param moduleMap {Object}: Module map, see buildModulesString()
751 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
752 * @param sourceLoadScript {String}: URL of load.php
753 */
754 function doRequest( moduleMap, currReqBase, sourceLoadScript ) {
755 var request = $.extend(
756 { 'modules': buildModulesString( moduleMap ) },
757 currReqBase
758 );
759 request = sortQuery( request );
760 // Asynchronously append a script tag to the end of the body
761 // Append &* to avoid triggering the IE6 extension check
762 addScript( sourceLoadScript + '?' + $.param( request ) + '&*' );
763 }
764
765 /* Public Methods */
766
767 /**
768 * Requests dependencies from server, loading and executing when things when ready.
769 */
770 this.work = function() {
771 // Build a list of request parameters common to all requests.
772 var reqBase = {
773 skin: mw.config.get( 'skin' ),
774 lang: mw.config.get( 'wgUserLanguage' ),
775 debug: mw.config.get( 'debug' )
776 },
777 // Split module batch by source and by group.
778 splits = {},
779 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
780
781 // Appends a list of modules from the queue to the batch
782 for ( var q = 0; q < queue.length; q++ ) {
783 // Only request modules which are undefined or registered
784 if ( !( queue[q] in registry ) || registry[queue[q]].state === 'registered' ) {
785 // Prevent duplicate entries
786 if ( $.inArray( queue[q], batch ) === -1 ) {
787 batch[batch.length] = queue[q];
788 // Mark registered modules as loading
789 if ( queue[q] in registry ) {
790 registry[queue[q]].state = 'loading';
791 }
792 }
793 }
794 }
795 // Early exit if there's nothing to load...
796 if ( !batch.length ) {
797 return;
798 }
799
800 // The queue has been processed into the batch, clear up the queue.
801 queue = [];
802
803 // Always order modules alphabetically to help reduce cache
804 // misses for otherwise identical content.
805 batch.sort();
806
807 // Split batch by source and by group.
808 for ( var b = 0; b < batch.length; b++ ) {
809 var bSource = registry[batch[b]].source,
810 bGroup = registry[batch[b]].group;
811 if ( !( bSource in splits ) ) {
812 splits[bSource] = {};
813 }
814 if ( !( bGroup in splits[bSource] ) ) {
815 splits[bSource][bGroup] = [];
816 }
817 var bSourceGroup = splits[bSource][bGroup];
818 bSourceGroup[bSourceGroup.length] = batch[b];
819 }
820
821 // Clear the batch - this MUST happen before we append any
822 // script elements to the body or it's possible that a script
823 // will be locally cached, instantly load, and work the batch
824 // again, all before we've cleared it causing each request to
825 // include modules which are already loaded.
826 batch = [];
827
828 var source, group, modules, maxVersion, sourceLoadScript;
829
830 for ( source in splits ) {
831
832 sourceLoadScript = sources[source].loadScript;
833
834 for ( group in splits[source] ) {
835
836 // Cache access to currently selected list of
837 // modules for this group from this source.
838 modules = splits[source][group];
839
840 // Calculate the highest timestamp
841 maxVersion = 0;
842 for ( var g = 0; g < modules.length; g++ ) {
843 if ( registry[modules[g]].version > maxVersion ) {
844 maxVersion = registry[modules[g]].version;
845 }
846 }
847
848 var currReqBase = $.extend( { 'version': formatVersionNumber( maxVersion ) }, reqBase ),
849 currReqBaseLength = $.param( currReqBase ).length,
850 moduleMap = {},
851 // We may need to split up the request to honor the query string length limit,
852 // so build it piece by piece.
853 l = currReqBaseLength + 9; // '&modules='.length == 9
854
855 moduleMap = {}; // { prefix: [ suffixes ] }
856
857 for ( var i = 0; i < modules.length; i++ ) {
858 // Determine how many bytes this module would add to the query string
859 var lastDotIndex = modules[i].lastIndexOf( '.' ),
860 // Note that these substr() calls work even if lastDotIndex == -1
861 prefix = modules[i].substr( 0, lastDotIndex ),
862 suffix = modules[i].substr( lastDotIndex + 1 ),
863 bytesAdded = prefix in moduleMap
864 ? suffix.length + 3 // '%2C'.length == 3
865 : modules[i].length + 3; // '%7C'.length == 3
866
867 // If the request would become too long, create a new one,
868 // but don't create empty requests
869 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
870 // This request would become too long, create a new one
871 // and fire off the old one
872 doRequest( moduleMap, currReqBase, sourceLoadScript );
873 moduleMap = {};
874 l = currReqBaseLength + 9;
875 }
876 if ( !( prefix in moduleMap ) ) {
877 moduleMap[prefix] = [];
878 }
879 moduleMap[prefix].push( suffix );
880 l += bytesAdded;
881 }
882 // If there's anything left in moduleMap, request that too
883 if ( !$.isEmptyObject( moduleMap ) ) {
884 doRequest( moduleMap, currReqBase, sourceLoadScript );
885 }
886 }
887 }
888 };
889
890 /**
891 * Register a source.
892 *
893 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
894 * @param props {Object}: Object containing only the loadScript property which is a url to
895 * the load.php location of the source.
896 * @return {Boolean}
897 */
898 this.addSource = function( id, props ) {
899 // Allow multiple additions
900 if ( typeof id === 'object' ) {
901 for ( var source in id ) {
902 mw.loader.addSource( source, id[source] );
903 }
904 return true;
905 }
906
907 if ( sources[id] !== undefined ) {
908 throw new Error( 'source already registered: ' + id );
909 }
910
911 sources[id] = props;
912
913 return true;
914 };
915
916 /**
917 * Registers a module, letting the system know about it and its
918 * properties. Startup modules contain calls to this function.
919 *
920 * @param module {String}: Module name
921 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
922 * @param dependencies {String|Array|Function}: One string or array of strings of module
923 * names on which this module depends, or a function that returns that array.
924 * @param group {String}: Group which the module is in (optional, defaults to null)
925 * @param source {String}: Name of the source. Defaults to local.
926 */
927 this.register = function( module, version, dependencies, group, source ) {
928 // Allow multiple registration
929 if ( typeof module === 'object' ) {
930 for ( var m = 0; m < module.length; m++ ) {
931 // module is an array of module names
932 if ( typeof module[m] === 'string' ) {
933 mw.loader.register( module[m] );
934 // module is an array of arrays
935 } else if ( typeof module[m] === 'object' ) {
936 mw.loader.register.apply( mw.loader, module[m] );
937 }
938 }
939 return;
940 }
941 // Validate input
942 if ( typeof module !== 'string' ) {
943 throw new Error( 'module must be a string, not a ' + typeof module );
944 }
945 if ( registry[module] !== undefined ) {
946 throw new Error( 'module already implemented: ' + module );
947 }
948 // List the module as registered
949 registry[module] = {
950 'version': version !== undefined ? parseInt( version, 10 ) : 0,
951 'dependencies': [],
952 'group': typeof group === 'string' ? group : null,
953 'source': typeof source === 'string' ? source: 'local',
954 'state': 'registered'
955 };
956 if ( typeof dependencies === 'string' ) {
957 // Allow dependencies to be given as a single module name
958 registry[module].dependencies = [dependencies];
959 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
960 // Allow dependencies to be given as an array of module names
961 // or a function which returns an array
962 registry[module].dependencies = dependencies;
963 }
964 };
965
966 /**
967 * Implements a module, giving the system a course of action to take
968 * upon loading. Results of a request for one or more modules contain
969 * calls to this function.
970 *
971 * All arguments are required.
972 *
973 * @param module String: Name of module
974 * @param script Mixed: Function of module code or String of URL to be used as the src
975 * attribute when adding a script element to the body
976 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
977 * keyed by media-type
978 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
979 */
980 this.implement = function( module, script, style, msgs ) {
981 // Validate input
982 if ( typeof module !== 'string' ) {
983 throw new Error( 'module must be a string, not a ' + typeof module );
984 }
985 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
986 throw new Error( 'script must be a function or an array, not a ' + typeof script );
987 }
988 if ( !$.isPlainObject( style ) ) {
989 throw new Error( 'style must be an object, not a ' + typeof style );
990 }
991 if ( !$.isPlainObject( msgs ) ) {
992 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
993 }
994 // Automatically register module
995 if ( registry[module] === undefined ) {
996 mw.loader.register( module );
997 }
998 // Check for duplicate implementation
999 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1000 throw new Error( 'module already implemeneted: ' + module );
1001 }
1002 // Mark module as loaded
1003 registry[module].state = 'loaded';
1004 // Attach components
1005 registry[module].script = script;
1006 registry[module].style = style;
1007 registry[module].messages = msgs;
1008 // Execute or queue callback
1009 if ( compare(
1010 filter( ['ready'], registry[module].dependencies ),
1011 registry[module].dependencies ) )
1012 {
1013 execute( module );
1014 } else {
1015 request( module );
1016 }
1017 };
1018
1019 /**
1020 * Executes a function as soon as one or more required modules are ready
1021 *
1022 * @param dependencies string or array of strings of modules names the callback
1023 * dependencies to be ready before executing
1024 * @param ready function callback to execute when all dependencies are ready (optional)
1025 * @param error function callback to execute when if dependencies have a errors (optional)
1026 */
1027 this.using = function( dependencies, ready, error ) {
1028 var tod = typeof dependencies;
1029 // Validate input
1030 if ( tod !== 'object' && tod !== 'string' ) {
1031 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1032 }
1033 // Allow calling with a single dependency as a string
1034 if ( tod === 'string' ) {
1035 dependencies = [dependencies];
1036 }
1037 // Resolve entire dependency map
1038 dependencies = resolve( dependencies );
1039 // If all dependencies are met, execute ready immediately
1040 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
1041 if ( $.isFunction( ready ) ) {
1042 ready();
1043 }
1044 }
1045 // If any dependencies have errors execute error immediately
1046 else if ( filter( ['error'], dependencies ).length ) {
1047 if ( $.isFunction( error ) ) {
1048 error();
1049 }
1050 }
1051 // Since some dependencies are not yet ready, queue up a request
1052 else {
1053 request( dependencies, ready, error );
1054 }
1055 };
1056
1057 /**
1058 * Loads an external script or one or more modules for future use
1059 *
1060 * @param modules mixed either the name of a module, array of modules,
1061 * or a URL of an external script or style
1062 * @param type string mime-type to use if calling with a URL of an
1063 * external script or style; acceptable values are "text/css" and
1064 * "text/javascript"; if no type is provided, text/javascript is assumed.
1065 */
1066 this.load = function( modules, type ) {
1067 // Validate input
1068 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1069 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1070 }
1071 // Allow calling with an external script or single dependency as a string
1072 if ( typeof modules === 'string' ) {
1073 // Support adding arbitrary external scripts
1074 if ( modules.substr( 0, 7 ) === 'http://' || modules.substr( 0, 8 ) === 'https://' || modules.substr( 0, 2 ) === '//' ) {
1075 if ( type === 'text/css' ) {
1076 $( 'head' ).append( $( '<link/>', {
1077 rel: 'stylesheet',
1078 type: 'text/css',
1079 href: modules
1080 } ) );
1081 return true;
1082 } else if ( type === 'text/javascript' || type === undefined ) {
1083 addScript( modules );
1084 return true;
1085 }
1086 // Unknown type
1087 return false;
1088 }
1089 // Called with single module
1090 modules = [modules];
1091 }
1092 // Resolve entire dependency map
1093 modules = resolve( modules );
1094 // If all modules are ready, nothing dependency be done
1095 if ( compare( filter( ['ready'], modules ), modules ) ) {
1096 return true;
1097 }
1098 // If any modules have errors return false
1099 else if ( filter( ['error'], modules ).length ) {
1100 return false;
1101 }
1102 // Since some modules are not yet ready, queue up a request
1103 else {
1104 request( modules );
1105 return true;
1106 }
1107 };
1108
1109 /**
1110 * Changes the state of a module
1111 *
1112 * @param module string module name or object of module name/state pairs
1113 * @param state string state name
1114 */
1115 this.state = function( module, state ) {
1116 if ( typeof module === 'object' ) {
1117 for ( var m in module ) {
1118 mw.loader.state( m, module[m] );
1119 }
1120 return;
1121 }
1122 if ( !( module in registry ) ) {
1123 mw.loader.register( module );
1124 }
1125 registry[module].state = state;
1126 };
1127
1128 /**
1129 * Gets the version of a module
1130 *
1131 * @param module string name of module to get version for
1132 */
1133 this.getVersion = function( module ) {
1134 if ( module in registry && 'version' in registry[module] ) {
1135 return formatVersionNumber( registry[module].version );
1136 }
1137 return null;
1138 };
1139
1140 /**
1141 * @deprecated use mw.loader.getVersion() instead
1142 */
1143 this.version = function() {
1144 return mw.loader.getVersion.apply( mw.loader, arguments );
1145 };
1146
1147 /**
1148 * Gets the state of a module
1149 *
1150 * @param module string name of module to get state for
1151 */
1152 this.getState = function( module ) {
1153 if ( module in registry && 'state' in registry[module] ) {
1154 return registry[module].state;
1155 }
1156 return null;
1157 };
1158
1159 /**
1160 * Get names of all registered modules.
1161 *
1162 * @return {Array}
1163 */
1164 this.getModuleNames = function() {
1165 var names = $.map( registry, function( i, key ) {
1166 return key;
1167 } );
1168 return names;
1169 };
1170
1171 /* Cache document ready status */
1172
1173 $(document).ready( function() { ready = true; } );
1174 } )();
1175
1176 /** HTML construction helper functions */
1177 this.html = new ( function () {
1178 var escapeCallback = function( s ) {
1179 switch ( s ) {
1180 case "'":
1181 return '&#039;';
1182 case '"':
1183 return '&quot;';
1184 case '<':
1185 return '&lt;';
1186 case '>':
1187 return '&gt;';
1188 case '&':
1189 return '&amp;';
1190 }
1191 };
1192
1193 /**
1194 * Escape a string for HTML. Converts special characters to HTML entities.
1195 * @param s The string to escape
1196 */
1197 this.escape = function( s ) {
1198 return s.replace( /['"<>&]/g, escapeCallback );
1199 };
1200
1201 /**
1202 * Wrapper object for raw HTML passed to mw.html.element().
1203 */
1204 this.Raw = function( value ) {
1205 this.value = value;
1206 };
1207
1208 /**
1209 * Wrapper object for CDATA element contents passed to mw.html.element()
1210 */
1211 this.Cdata = function( value ) {
1212 this.value = value;
1213 };
1214
1215 /**
1216 * Create an HTML element string, with safe escaping.
1217 *
1218 * @param name The tag name.
1219 * @param attrs An object with members mapping element names to values
1220 * @param contents The contents of the element. May be either:
1221 * - string: The string is escaped.
1222 * - null or undefined: The short closing form is used, e.g. <br/>.
1223 * - this.Raw: The value attribute is included without escaping.
1224 * - this.Cdata: The value attribute is included, and an exception is
1225 * thrown if it contains an illegal ETAGO delimiter.
1226 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1227 *
1228 * Example:
1229 * var h = mw.html;
1230 * return h.element( 'div', {},
1231 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1232 * Returns <div><img src="&lt;"/></div>
1233 */
1234 this.element = function( name, attrs, contents ) {
1235 var s = '<' + name;
1236 for ( var attrName in attrs ) {
1237 s += ' ' + attrName + '="' + this.escape( attrs[attrName] ) + '"';
1238 }
1239 if ( contents === undefined || contents === null ) {
1240 // Self close tag
1241 s += '/>';
1242 return s;
1243 }
1244 // Regular open tag
1245 s += '>';
1246 if ( typeof contents === 'string' ) {
1247 // Escaped
1248 s += this.escape( contents );
1249 } else if ( contents instanceof this.Raw ) {
1250 // Raw HTML inclusion
1251 s += contents.value;
1252 } else if ( contents instanceof this.Cdata ) {
1253 // CDATA
1254 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1255 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1256 }
1257 s += contents.value;
1258 } else {
1259 throw new Error( 'mw.html.element: Invalid type of contents' );
1260 }
1261 s += '</' + name + '>';
1262 return s;
1263 };
1264 } )();
1265
1266 /* Extension points */
1267
1268 this.legacy = {};
1269
1270 } )( jQuery );
1271
1272 // Alias $j to jQuery for backwards compatibility
1273 window.$j = jQuery;
1274
1275 // Auto-register from pre-loaded startup scripts
1276 if ( jQuery.isFunction( startUp ) ) {
1277 startUp();
1278 delete startUp;
1279 }