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