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