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