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