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