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