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