fix for bug 34696 - mw.loader.using shouldnt call callback more than once
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /*jslint browser: true, continue: true, white: true, forin: true*/
2 /*global jQuery*/
3 /*
4 * Core MediaWiki JavaScript Library
5 */
6
7 var mw = ( function ( $, undefined ) {
8 "use strict";
9
10 /* Private Members */
11
12 var hasOwn = Object.prototype.hasOwnProperty;
13 /* Object constructors */
14
15 /**
16 * Map
17 *
18 * Creates an object that can be read from or written to from prototype functions
19 * that allow both single and multiple variables at once.
20 *
21 * @param global boolean Whether to store the values in the global window
22 * object or a exclusively in the object property 'values'.
23 * @return Map
24 */
25 function Map( global ) {
26 this.values = global === true ? window : {};
27 return this;
28 }
29
30 Map.prototype = {
31 /**
32 * Get the value of one or multiple a keys.
33 *
34 * If called with no arguments, all values will be returned.
35 *
36 * @param selection mixed String key or array of keys to get values for.
37 * @param fallback mixed Value to use in case key(s) do not exist (optional).
38 * @return mixed If selection was a string returns the value or null,
39 * If selection was an array, returns an object of key/values (value is null if not found),
40 * If selection was not passed or invalid, will return the 'values' object member (be careful as
41 * objects are always passed by reference in JavaScript!).
42 * @return Values as a string or object, null if invalid/inexistant.
43 */
44 get: function ( selection, fallback ) {
45 var results, i;
46
47 if ( $.isArray( selection ) ) {
48 selection = $.makeArray( selection );
49 results = {};
50 for ( i = 0; i < selection.length; i += 1 ) {
51 results[selection[i]] = this.get( selection[i], fallback );
52 }
53 return results;
54 }
55
56 if ( typeof selection === 'string' ) {
57 if ( this.values[selection] === undefined ) {
58 if ( fallback !== undefined ) {
59 return fallback;
60 }
61 return null;
62 }
63 return this.values[selection];
64 }
65
66 if ( selection === undefined ) {
67 return this.values;
68 }
69
70 // invalid selection key
71 return null;
72 },
73
74 /**
75 * Sets one or multiple key/value pairs.
76 *
77 * @param selection {mixed} String key or array of keys to set values for.
78 * @param value {mixed} Value to set (optional, only in use when key is a string)
79 * @return {Boolean} This returns true on success, false on failure.
80 */
81 set: function ( selection, value ) {
82 var s;
83
84 if ( $.isPlainObject( selection ) ) {
85 for ( s in selection ) {
86 this.values[s] = selection[s];
87 }
88 return true;
89 }
90 if ( typeof selection === 'string' && value !== undefined ) {
91 this.values[selection] = value;
92 return true;
93 }
94 return false;
95 },
96
97 /**
98 * Checks if one or multiple keys exist.
99 *
100 * @param selection {mixed} String key or array of keys to check
101 * @return {Boolean} Existence of key(s)
102 */
103 exists: function ( selection ) {
104 var s;
105
106 if ( $.isArray( selection ) ) {
107 for ( s = 0; s < selection.length; s += 1 ) {
108 if ( this.values[selection[s]] === undefined ) {
109 return false;
110 }
111 }
112 return true;
113 }
114 return this.values[selection] !== undefined;
115 }
116 };
117
118 /**
119 * Message
120 *
121 * Object constructor for messages,
122 * similar to the Message class in MediaWiki PHP.
123 *
124 * @param map Map Instance of mw.Map
125 * @param key String
126 * @param parameters Array
127 * @return Message
128 */
129 function Message( map, key, parameters ) {
130 this.format = 'plain';
131 this.map = map;
132 this.key = key;
133 this.parameters = parameters === undefined ? [] : $.makeArray( parameters );
134 return this;
135 }
136
137 Message.prototype = {
138 /**
139 * Simple message parser, does $N replacement and nothing else.
140 * This may be overridden to provide a more complex message parser.
141 *
142 * This function will not be called for nonexistent messages.
143 */
144 parser: function() {
145 var parameters = this.parameters;
146 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
147 var index = parseInt( match, 10 ) - 1;
148 return parameters[index] !== undefined ? parameters[index] : '$' + match;
149 } );
150 },
151
152 /**
153 * Appends (does not replace) parameters for replacement to the .parameters property.
154 *
155 * @param parameters Array
156 * @return Message
157 */
158 params: function ( parameters ) {
159 var i;
160 for ( i = 0; i < parameters.length; i += 1 ) {
161 this.parameters.push( parameters[i] );
162 }
163 return this;
164 },
165
166 /**
167 * Converts message object to it's string form based on the state of format.
168 *
169 * @return string Message as a string in the current form or <key> if key does not exist.
170 */
171 toString: function() {
172 var text;
173
174 if ( !this.exists() ) {
175 // Use <key> as text if key does not exist
176 if ( this.format !== 'plain' ) {
177 // format 'escape' and 'parse' need to have the brackets and key html escaped
178 return mw.html.escape( '<' + this.key + '>' );
179 }
180 return '<' + this.key + '>';
181 }
182
183 if ( this.format === 'plain' ) {
184 // @todo FIXME: Although not applicable to core Message,
185 // Plugins like jQueryMsg should be able to distinguish
186 // between 'plain' (only variable replacement and plural/gender)
187 // and actually parsing wikitext to HTML.
188 text = this.parser();
189 }
190
191 if ( this.format === 'escaped' ) {
192 text = this.parser();
193 text = mw.html.escape( text );
194 }
195
196 if ( this.format === 'parse' ) {
197 text = this.parser();
198 }
199
200 return text;
201 },
202
203 /**
204 * Changes format to parse and converts message to string
205 *
206 * @return {string} String form of parsed message
207 */
208 parse: function() {
209 this.format = 'parse';
210 return this.toString();
211 },
212
213 /**
214 * Changes format to plain and converts message to string
215 *
216 * @return {string} String form of plain message
217 */
218 plain: function() {
219 this.format = 'plain';
220 return this.toString();
221 },
222
223 /**
224 * Changes the format to html escaped and converts message to string
225 *
226 * @return {string} String form of html escaped message
227 */
228 escaped: function() {
229 this.format = 'escaped';
230 return this.toString();
231 },
232
233 /**
234 * Checks if message exists
235 *
236 * @return {string} String form of parsed message
237 */
238 exists: function() {
239 return this.map.exists( this.key );
240 }
241 };
242
243 return {
244 /* Public Members */
245
246 /**
247 * Dummy function which in debug mode can be replaced with a function that
248 * emulates console.log in console-less environments.
249 */
250 log: function() { },
251
252 /**
253 * @var constructor Make the Map constructor publicly available.
254 */
255 Map: Map,
256
257 /**
258 * @var constructor Make the Message constructor publicly available.
259 */
260 Message: Message,
261
262 /**
263 * List of configuration values
264 *
265 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
266 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
267 * in the global window object.
268 */
269 config: null,
270
271 /**
272 * @var object
273 *
274 * Empty object that plugins can be installed in.
275 */
276 libs: {},
277
278 /* Extension points */
279
280 legacy: {},
281
282 /**
283 * Localization system
284 */
285 messages: new Map(),
286
287 /* Public Methods */
288
289 /**
290 * Gets a message object, similar to wfMessage()
291 *
292 * @param key string Key of message to get
293 * @param parameter_1 mixed First argument in a list of variadic arguments,
294 * each a parameter for $N replacement in messages.
295 * @return Message
296 */
297 message: function ( key, parameter_1 /* [, parameter_2] */ ) {
298 var parameters;
299 // Support variadic arguments
300 if ( parameter_1 !== undefined ) {
301 parameters = $.makeArray( arguments );
302 parameters.shift();
303 } else {
304 parameters = [];
305 }
306 return new Message( mw.messages, key, parameters );
307 },
308
309 /**
310 * Gets a message string, similar to wfMsg()
311 *
312 * @param key string Key of message to get
313 * @param parameters mixed First argument in a list of variadic arguments,
314 * each a parameter for $N replacement in messages.
315 * @return String.
316 */
317 msg: function ( /* key, parameter_1, parameter_2, .. */ ) {
318 return mw.message.apply( mw.message, arguments ).toString();
319 },
320
321 /**
322 * Client-side module loader which integrates with the MediaWiki ResourceLoader
323 */
324 loader: ( function () {
325
326 /* Private Members */
327
328 /**
329 * Mapping of registered modules
330 *
331 * The jquery module is pre-registered, because it must have already
332 * been provided for this object to have been built, and in debug mode
333 * jquery would have been provided through a unique loader request,
334 * making it impossible to hold back registration of jquery until after
335 * mediawiki.
336 *
337 * For exact details on support for script, style and messages, look at
338 * mw.loader.implement.
339 *
340 * Format:
341 * {
342 * 'moduleName': {
343 * 'version': ############## (unix timestamp),
344 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
345 * 'group': 'somegroup', (or) null,
346 * 'source': 'local', 'someforeignwiki', (or) null
347 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
348 * 'script': ...,
349 * 'style': ...,
350 * 'messages': { 'key': 'value' },
351 * }
352 * }
353 */
354 var registry = {},
355 /**
356 * Mapping of sources, keyed by source-id, values are objects.
357 * Format:
358 * {
359 * 'sourceId': {
360 * 'loadScript': 'http://foo.bar/w/load.php'
361 * }
362 * }
363 */
364 sources = {},
365 // List of modules which will be loaded as when ready
366 batch = [],
367 // List of modules to be loaded
368 queue = [],
369 // List of callback functions waiting for modules to be ready to be called
370 jobs = [],
371 // Flag indicating that document ready has occured
372 ready = false,
373 // Selector cache for the marker element. Use getMarker() to get/use the marker!
374 $marker = null;
375
376 /* Cache document ready status */
377
378 $(document).ready( function () {
379 ready = true;
380 } );
381
382 /* Private methods */
383
384 function getMarker() {
385 // Cached ?
386 if ( $marker ) {
387 return $marker;
388 }
389
390 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
391 if ( $marker.length ) {
392 return $marker;
393 }
394 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
395 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
396
397 return $marker;
398 }
399
400 /**
401 * Create a new style tag and add it to the DOM.
402 *
403 * @param text String: CSS text
404 * @param $nextnode mixed: [optional] An Element or jQuery object for an element where
405 * the style tag should be inserted before. Otherwise appended to the <head>.
406 * @return HTMLStyleElement
407 */
408 function addStyleTag( text, $nextnode ) {
409 var s = document.createElement( 'style' );
410 s.type = 'text/css';
411 s.rel = 'stylesheet';
412 // Insert into document before setting cssText (bug 33305)
413 if ( $nextnode ) {
414 // If a raw element, create a jQuery object, otherwise use directly
415 if ( $nextnode.nodeType ) {
416 $nextnode = $( $nextnode );
417 }
418 $nextnode.before( s );
419 } else {
420 document.getElementsByTagName('head')[0].appendChild( s );
421 }
422 if ( s.styleSheet ) {
423 s.styleSheet.cssText = text; // IE
424 } else {
425 // Safari sometimes borks on null
426 s.appendChild( document.createTextNode( String( text ) ) );
427 }
428 return s;
429 }
430
431 function addInlineCSS( css ) {
432 var $style, style, $newStyle;
433 $style = getMarker().prev();
434 if ( $style.is( 'style' ) && $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
435 // There's already a dynamic <style> tag present, append to it. This recycling of
436 // <style> tags is for bug 31676 (can't have more than 32 <style> tags in IE)
437 style = $style.get( 0 );
438 if ( style.styleSheet ) {
439 style.styleSheet.cssText += css; // IE
440 } else {
441 style.appendChild( document.createTextNode( String( css ) ) );
442 }
443 } else {
444 $newStyle = $( addStyleTag( css, getMarker() ) )
445 .data( 'ResourceLoaderDynamicStyleTag', true );
446 }
447 }
448
449 function compare( a, b ) {
450 var i;
451 if ( a.length !== b.length ) {
452 return false;
453 }
454 for ( i = 0; i < b.length; i += 1 ) {
455 if ( $.isArray( a[i] ) ) {
456 if ( !compare( a[i], b[i] ) ) {
457 return false;
458 }
459 }
460 if ( a[i] !== b[i] ) {
461 return false;
462 }
463 }
464 return true;
465 }
466
467 /**
468 * Generates an ISO8601 "basic" string from a UNIX timestamp
469 */
470 function formatVersionNumber( timestamp ) {
471 var pad = function ( a, b, c ) {
472 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
473 },
474 d = new Date();
475 d.setTime( timestamp * 1000 );
476 return [
477 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
478 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
479 ].join( '' );
480 }
481
482 /**
483 * Recursively resolves dependencies and detects circular references
484 */
485 function recurse( module, resolved, unresolved ) {
486 var n, deps, len;
487
488 if ( registry[module] === undefined ) {
489 throw new Error( 'Unknown dependency: ' + module );
490 }
491 // Resolves dynamic loader function and replaces it with its own results
492 if ( $.isFunction( registry[module].dependencies ) ) {
493 registry[module].dependencies = registry[module].dependencies();
494 // Ensures the module's dependencies are always in an array
495 if ( typeof registry[module].dependencies !== 'object' ) {
496 registry[module].dependencies = [registry[module].dependencies];
497 }
498 }
499 // Tracks down dependencies
500 deps = registry[module].dependencies;
501 len = deps.length;
502 for ( n = 0; n < len; n += 1 ) {
503 if ( $.inArray( deps[n], resolved ) === -1 ) {
504 if ( $.inArray( deps[n], unresolved ) !== -1 ) {
505 throw new Error(
506 'Circular reference detected: ' + module +
507 ' -> ' + deps[n]
508 );
509 }
510
511 // Add to unresolved
512 unresolved[unresolved.length] = module;
513 recurse( deps[n], resolved, unresolved );
514 // module is at the end of unresolved
515 unresolved.pop();
516 }
517 }
518 resolved[resolved.length] = module;
519 }
520
521 /**
522 * Gets a list of module names that a module depends on in their proper dependency order
523 *
524 * @param module string module name or array of string module names
525 * @return list of dependencies, including 'module'.
526 * @throws Error if circular reference is detected
527 */
528 function resolve( module ) {
529 var modules, m, deps, n, resolved;
530
531 // Allow calling with an array of module names
532 if ( $.isArray( module ) ) {
533 modules = [];
534 for ( m = 0; m < module.length; m += 1 ) {
535 deps = resolve( module[m] );
536 for ( n = 0; n < deps.length; n += 1 ) {
537 modules[modules.length] = deps[n];
538 }
539 }
540 return modules;
541 }
542
543 if ( typeof module === 'string' ) {
544 resolved = [];
545 recurse( module, resolved, [] );
546 return resolved;
547 }
548
549 throw new Error( 'Invalid module argument: ' + module );
550 }
551
552 /**
553 * Narrows a list of module names down to those matching a specific
554 * state (see comment on top of this scope for a list of valid states).
555 * One can also filter for 'unregistered', which will return the
556 * modules names that don't have a registry entry.
557 *
558 * @param states string or array of strings of module states to filter by
559 * @param modules array list of module names to filter (optional, by default the entire
560 * registry is used)
561 * @return array list of filtered module names
562 */
563 function filter( states, modules ) {
564 var list, module, s, m;
565
566 // Allow states to be given as a string
567 if ( typeof states === 'string' ) {
568 states = [states];
569 }
570 // If called without a list of modules, build and use a list of all modules
571 list = [];
572 if ( modules === undefined ) {
573 modules = [];
574 for ( module in registry ) {
575 modules[modules.length] = module;
576 }
577 }
578 // Build a list of modules which are in one of the specified states
579 for ( s = 0; s < states.length; s += 1 ) {
580 for ( m = 0; m < modules.length; m += 1 ) {
581 if ( registry[modules[m]] === undefined ) {
582 // Module does not exist
583 if ( states[s] === 'unregistered' ) {
584 // OK, undefined
585 list[list.length] = modules[m];
586 }
587 } else {
588 // Module exists, check state
589 if ( registry[modules[m]].state === states[s] ) {
590 // OK, correct state
591 list[list.length] = modules[m];
592 }
593 }
594 }
595 }
596 return list;
597 }
598
599 /**
600 * Automatically executes jobs and modules which are pending with satistifed dependencies.
601 *
602 * This is used when dependencies are satisfied, such as when a module is executed.
603 */
604 function handlePending( module ) {
605 var j, r;
606
607 try {
608 // Run jobs whose dependencies have just been met
609 for ( j = 0; j < jobs.length; j += 1 ) {
610 if ( compare(
611 filter( 'ready', jobs[j].dependencies ),
612 jobs[j].dependencies ) )
613 {
614 var callback = jobs[j].ready;
615 jobs.splice( j, 1 );
616 j -= 1;
617 if ( $.isFunction( callback ) ) {
618 callback();
619 }
620 }
621 }
622 // Execute modules whose dependencies have just been met
623 for ( r in registry ) {
624 if ( registry[r].state === 'loaded' ) {
625 if ( compare(
626 filter( ['ready'], registry[r].dependencies ),
627 registry[r].dependencies ) )
628 {
629 execute( r );
630 }
631 }
632 }
633 } catch ( e ) {
634 // Run error callbacks of jobs affected by this condition
635 for ( j = 0; j < jobs.length; j += 1 ) {
636 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
637 if ( $.isFunction( jobs[j].error ) ) {
638 jobs[j].error( e, module );
639 }
640 jobs.splice( j, 1 );
641 j -= 1;
642 }
643 }
644 throw e;
645 }
646 }
647
648 /**
649 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
650 * depending on whether document-ready has occured yet and whether we are in async mode.
651 *
652 * @param src String: URL to script, will be used as the src attribute in the script tag
653 * @param callback Function: Optional callback which will be run when the script is done
654 */
655 function addScript( src, callback, async ) {
656 var done = false, script, head;
657 if ( ready || async ) {
658 // jQuery's getScript method is NOT better than doing this the old-fashioned way
659 // because jQuery will eval the script's code, and errors will not have sane
660 // line numbers.
661 script = document.createElement( 'script' );
662 script.setAttribute( 'src', src );
663 script.setAttribute( 'type', 'text/javascript' );
664 if ( $.isFunction( callback ) ) {
665 // Attach handlers for all browsers (based on jQuery.ajax)
666 script.onload = script.onreadystatechange = function() {
667
668 if (
669 !done
670 && (
671 !script.readyState
672 || /loaded|complete/.test( script.readyState )
673 )
674 ) {
675
676 done = true;
677
678 callback();
679
680 // Handle memory leak in IE. This seems to fail in
681 // IE7 sometimes (Permission Denied error when
682 // accessing script.parentNode) so wrap it in
683 // a try catch.
684 try {
685 script.onload = script.onreadystatechange = null;
686 if ( script.parentNode ) {
687 script.parentNode.removeChild( script );
688 }
689
690 // Dereference the script
691 script = undefined;
692 } catch ( e ) { }
693 }
694 };
695 }
696
697 if ( window.opera ) {
698 // Appending to the <head> blocks rendering completely in Opera,
699 // so append to the <body> after document ready. This means the
700 // scripts only start loading after the document has been rendered,
701 // but so be it. Opera users don't deserve faster web pages if their
702 // browser makes it impossible
703 $( function() { document.body.appendChild( script ); } );
704 } else {
705 // IE-safe way of getting the <head> . document.documentElement.head doesn't
706 // work in scripts that run in the <head>
707 head = document.getElementsByTagName( 'head' )[0];
708 ( document.body || head ).appendChild( script );
709 }
710 } else {
711 document.write( mw.html.element(
712 'script', { 'type': 'text/javascript', 'src': src }, ''
713 ) );
714 if ( $.isFunction( callback ) ) {
715 // Document.write is synchronous, so this is called when it's done
716 // FIXME: that's a lie. doc.write isn't actually synchronous
717 callback();
718 }
719 }
720 }
721
722 /**
723 * Executes a loaded module, making it ready to use
724 *
725 * @param module string module name to execute
726 */
727 function execute( module, callback ) {
728 var style, media, i, script, markModuleReady, nestedAddScript;
729
730 if ( registry[module] === undefined ) {
731 throw new Error( 'Module has not been registered yet: ' + module );
732 } else if ( registry[module].state === 'registered' ) {
733 throw new Error( 'Module has not been requested from the server yet: ' + module );
734 } else if ( registry[module].state === 'loading' ) {
735 throw new Error( 'Module has not completed loading yet: ' + module );
736 } else if ( registry[module].state === 'ready' ) {
737 throw new Error( 'Module has already been loaded: ' + module );
738 }
739
740 // Add styles
741 if ( $.isPlainObject( registry[module].style ) ) {
742 // 'media' type ignored, see documentation of mw.loader.implement
743 for ( media in registry[module].style ) {
744 style = registry[module].style[media];
745 if ( $.isArray( style ) ) {
746 for ( i = 0; i < style.length; i += 1 ) {
747 getMarker().before( mw.html.element( 'link', {
748 'type': 'text/css',
749 'rel': 'stylesheet',
750 'href': style[i]
751 } ) );
752 }
753 } else if ( typeof style === 'string' ) {
754 addInlineCSS( style );
755 }
756 }
757 }
758 // Add localizations to message system
759 if ( $.isPlainObject( registry[module].messages ) ) {
760 mw.messages.set( registry[module].messages );
761 }
762 // Execute script
763 try {
764 script = registry[module].script;
765 markModuleReady = function() {
766 registry[module].state = 'ready';
767 handlePending( module );
768 if ( $.isFunction( callback ) ) {
769 callback();
770 }
771 };
772 nestedAddScript = function ( arr, callback, async, i ) {
773 // Recursively call addScript() in its own callback
774 // for each element of arr.
775 if ( i >= arr.length ) {
776 // We're at the end of the array
777 callback();
778 return;
779 }
780
781 addScript( arr[i], function() {
782 nestedAddScript( arr, callback, async, i + 1 );
783 }, async );
784 };
785
786 if ( $.isArray( script ) ) {
787 registry[module].state = 'loading';
788 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
789 } else if ( $.isFunction( script ) ) {
790 script();
791 markModuleReady();
792 }
793 } catch ( e ) {
794 // This needs to NOT use mw.log because these errors are common in production mode
795 // and not in debug mode, such as when a symbol that should be global isn't exported
796 if ( window.console && typeof window.console.log === 'function' ) {
797 console.log( 'mw.loader::execute> Exception thrown by ' + module + ': ' + e.message );
798 console.log( e );
799 }
800 registry[module].state = 'error';
801 }
802 }
803
804 /**
805 * Adds a dependencies to the queue with optional callbacks to be run
806 * when the dependencies are ready or fail
807 *
808 * @param dependencies string module name or array of string module names
809 * @param ready function callback to execute when all dependencies are ready
810 * @param error function callback to execute when any dependency fails
811 * @param async (optional) If true, load modules asynchronously even if
812 * document ready has not yet occurred
813 */
814 function request( dependencies, ready, error, async ) {
815 var regItemDeps, regItemDepLen, n;
816
817 // Allow calling by single module name
818 if ( typeof dependencies === 'string' ) {
819 dependencies = [dependencies];
820 if ( registry[dependencies[0]] !== undefined ) {
821 // Cache repetitively accessed deep level object member
822 regItemDeps = registry[dependencies[0]].dependencies;
823 // Cache to avoid looped access to length property
824 regItemDepLen = regItemDeps.length;
825 for ( n = 0; n < regItemDepLen; n += 1 ) {
826 dependencies[dependencies.length] = regItemDeps[n];
827 }
828 }
829 }
830
831 // Add ready and error callbacks if they were given
832 if ( ready !== undefined || error !== undefined ) {
833 jobs[jobs.length] = {
834 'dependencies': filter(
835 ['registered', 'loading', 'loaded'],
836 dependencies
837 ),
838 'ready': ready,
839 'error': error
840 };
841 }
842
843 // Queue up any dependencies that are registered
844 dependencies = filter( ['registered'], dependencies );
845 for ( n = 0; n < dependencies.length; n += 1 ) {
846 if ( $.inArray( dependencies[n], queue ) === -1 ) {
847 queue[queue.length] = dependencies[n];
848 if ( async ) {
849 // Mark this module as async in the registry
850 registry[dependencies[n]].async = true;
851 }
852 }
853 }
854
855 // Work the queue
856 mw.loader.work();
857 }
858
859 function sortQuery(o) {
860 var sorted = {}, key, a = [];
861 for ( key in o ) {
862 if ( hasOwn.call( o, key ) ) {
863 a.push( key );
864 }
865 }
866 a.sort();
867 for ( key = 0; key < a.length; key += 1 ) {
868 sorted[a[key]] = o[a[key]];
869 }
870 return sorted;
871 }
872
873 /**
874 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
875 * to a query string of the form foo.bar,baz|bar.baz,quux
876 */
877 function buildModulesString( moduleMap ) {
878 var arr = [], p, prefix;
879 for ( prefix in moduleMap ) {
880 p = prefix === '' ? '' : prefix + '.';
881 arr.push( p + moduleMap[prefix].join( ',' ) );
882 }
883 return arr.join( '|' );
884 }
885
886 /**
887 * Asynchronously append a script tag to the end of the body
888 * that invokes load.php
889 * @param moduleMap {Object}: Module map, see buildModulesString()
890 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
891 * @param sourceLoadScript {String}: URL of load.php
892 * @param async {Boolean}: If true, use an asynchrounous request even if document ready has not yet occurred
893 */
894 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
895 var request = $.extend(
896 { 'modules': buildModulesString( moduleMap ) },
897 currReqBase
898 );
899 request = sortQuery( request );
900 // Asynchronously append a script tag to the end of the body
901 // Append &* to avoid triggering the IE6 extension check
902 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
903 }
904
905 /* Public Methods */
906 return {
907 addStyleTag: addStyleTag,
908
909 /**
910 * Requests dependencies from server, loading and executing when things when ready.
911 */
912 work: function () {
913 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
914 source, group, g, i, modules, maxVersion, sourceLoadScript,
915 currReqBase, currReqBaseLength, moduleMap, l,
916 lastDotIndex, prefix, suffix, bytesAdded, async;
917
918 // Build a list of request parameters common to all requests.
919 reqBase = {
920 skin: mw.config.get( 'skin' ),
921 lang: mw.config.get( 'wgUserLanguage' ),
922 debug: mw.config.get( 'debug' )
923 };
924 // Split module batch by source and by group.
925 splits = {};
926 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
927
928 // Appends a list of modules from the queue to the batch
929 for ( q = 0; q < queue.length; q += 1 ) {
930 // Only request modules which are registered
931 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
932 // Prevent duplicate entries
933 if ( $.inArray( queue[q], batch ) === -1 ) {
934 batch[batch.length] = queue[q];
935 // Mark registered modules as loading
936 registry[queue[q]].state = 'loading';
937 }
938 }
939 }
940 // Early exit if there's nothing to load...
941 if ( !batch.length ) {
942 return;
943 }
944
945 // The queue has been processed into the batch, clear up the queue.
946 queue = [];
947
948 // Always order modules alphabetically to help reduce cache
949 // misses for otherwise identical content.
950 batch.sort();
951
952 // Split batch by source and by group.
953 for ( b = 0; b < batch.length; b += 1 ) {
954 bSource = registry[batch[b]].source;
955 bGroup = registry[batch[b]].group;
956 if ( splits[bSource] === undefined ) {
957 splits[bSource] = {};
958 }
959 if ( splits[bSource][bGroup] === undefined ) {
960 splits[bSource][bGroup] = [];
961 }
962 bSourceGroup = splits[bSource][bGroup];
963 bSourceGroup[bSourceGroup.length] = batch[b];
964 }
965
966 // Clear the batch - this MUST happen before we append any
967 // script elements to the body or it's possible that a script
968 // will be locally cached, instantly load, and work the batch
969 // again, all before we've cleared it causing each request to
970 // include modules which are already loaded.
971 batch = [];
972
973 for ( source in splits ) {
974
975 sourceLoadScript = sources[source].loadScript;
976
977 for ( group in splits[source] ) {
978
979 // Cache access to currently selected list of
980 // modules for this group from this source.
981 modules = splits[source][group];
982
983 // Calculate the highest timestamp
984 maxVersion = 0;
985 for ( g = 0; g < modules.length; g += 1 ) {
986 if ( registry[modules[g]].version > maxVersion ) {
987 maxVersion = registry[modules[g]].version;
988 }
989 }
990
991 currReqBase = $.extend( { 'version': formatVersionNumber( maxVersion ) }, reqBase );
992 currReqBaseLength = $.param( currReqBase ).length;
993 async = true;
994 // We may need to split up the request to honor the query string length limit,
995 // so build it piece by piece.
996 l = currReqBaseLength + 9; // '&modules='.length == 9
997
998 moduleMap = {}; // { prefix: [ suffixes ] }
999
1000 for ( i = 0; i < modules.length; i += 1 ) {
1001 // Determine how many bytes this module would add to the query string
1002 lastDotIndex = modules[i].lastIndexOf( '.' );
1003 // Note that these substr() calls work even if lastDotIndex == -1
1004 prefix = modules[i].substr( 0, lastDotIndex );
1005 suffix = modules[i].substr( lastDotIndex + 1 );
1006 bytesAdded = moduleMap[prefix] !== undefined
1007 ? suffix.length + 3 // '%2C'.length == 3
1008 : modules[i].length + 3; // '%7C'.length == 3
1009
1010 // If the request would become too long, create a new one,
1011 // but don't create empty requests
1012 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1013 // This request would become too long, create a new one
1014 // and fire off the old one
1015 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1016 moduleMap = {};
1017 async = true;
1018 l = currReqBaseLength + 9;
1019 }
1020 if ( moduleMap[prefix] === undefined ) {
1021 moduleMap[prefix] = [];
1022 }
1023 moduleMap[prefix].push( suffix );
1024 if ( !registry[modules[i]].async ) {
1025 // If this module is blocking, make the entire request blocking
1026 // This is slightly suboptimal, but in practice mixing of blocking
1027 // and async modules will only occur in debug mode.
1028 async = false;
1029 }
1030 l += bytesAdded;
1031 }
1032 // If there's anything left in moduleMap, request that too
1033 if ( !$.isEmptyObject( moduleMap ) ) {
1034 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1035 }
1036 }
1037 }
1038 },
1039
1040 /**
1041 * Register a source.
1042 *
1043 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
1044 * @param props {Object}: Object containing only the loadScript property which is a url to
1045 * the load.php location of the source.
1046 * @return {Boolean}
1047 */
1048 addSource: function ( id, props ) {
1049 var source;
1050 // Allow multiple additions
1051 if ( typeof id === 'object' ) {
1052 for ( source in id ) {
1053 mw.loader.addSource( source, id[source] );
1054 }
1055 return true;
1056 }
1057
1058 if ( sources[id] !== undefined ) {
1059 throw new Error( 'source already registered: ' + id );
1060 }
1061
1062 sources[id] = props;
1063
1064 return true;
1065 },
1066
1067 /**
1068 * Registers a module, letting the system know about it and its
1069 * properties. Startup modules contain calls to this function.
1070 *
1071 * @param module {String}: Module name
1072 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1073 * @param dependencies {String|Array|Function}: One string or array of strings of module
1074 * names on which this module depends, or a function that returns that array.
1075 * @param group {String}: Group which the module is in (optional, defaults to null)
1076 * @param source {String}: Name of the source. Defaults to local.
1077 */
1078 register: function ( module, version, dependencies, group, source ) {
1079 var m;
1080 // Allow multiple registration
1081 if ( typeof module === 'object' ) {
1082 for ( m = 0; m < module.length; m += 1 ) {
1083 // module is an array of module names
1084 if ( typeof module[m] === 'string' ) {
1085 mw.loader.register( module[m] );
1086 // module is an array of arrays
1087 } else if ( typeof module[m] === 'object' ) {
1088 mw.loader.register.apply( mw.loader, module[m] );
1089 }
1090 }
1091 return;
1092 }
1093 // Validate input
1094 if ( typeof module !== 'string' ) {
1095 throw new Error( 'module must be a string, not a ' + typeof module );
1096 }
1097 if ( registry[module] !== undefined ) {
1098 throw new Error( 'module already registered: ' + module );
1099 }
1100 // List the module as registered
1101 registry[module] = {
1102 'version': version !== undefined ? parseInt( version, 10 ) : 0,
1103 'dependencies': [],
1104 'group': typeof group === 'string' ? group : null,
1105 'source': typeof source === 'string' ? source: 'local',
1106 'state': 'registered'
1107 };
1108 if ( typeof dependencies === 'string' ) {
1109 // Allow dependencies to be given as a single module name
1110 registry[module].dependencies = [dependencies];
1111 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1112 // Allow dependencies to be given as an array of module names
1113 // or a function which returns an array
1114 registry[module].dependencies = dependencies;
1115 }
1116 },
1117
1118 /**
1119 * Implements a module, giving the system a course of action to take
1120 * upon loading. Results of a request for one or more modules contain
1121 * calls to this function.
1122 *
1123 * All arguments are required.
1124 *
1125 * @param module String: Name of module
1126 * @param script Mixed: Function of module code or String of URL to be used as the src
1127 * attribute when adding a script element to the body
1128 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1129 * keyed by media-type. Media-type should be "all" or "", actual types are not supported
1130 * right now due to the way execute() processes the stylesheets (they are concatenated
1131 * into a single <style> tag). In the past these weren't concatenated together (which is
1132 * these are keyed by media-type), but bug 31676 forces us to. In practice this is not a
1133 * problem because ResourceLoader only generates stylesheets for media-type all (e.g. print
1134 * stylesheets are wrapped in @media print {} and concatenated with the others).
1135 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1136 */
1137 implement: function ( module, script, style, msgs ) {
1138 // Validate input
1139 if ( typeof module !== 'string' ) {
1140 throw new Error( 'module must be a string, not a ' + typeof module );
1141 }
1142 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1143 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1144 }
1145 if ( !$.isPlainObject( style ) ) {
1146 throw new Error( 'style must be an object, not a ' + typeof style );
1147 }
1148 if ( !$.isPlainObject( msgs ) ) {
1149 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1150 }
1151 // Automatically register module
1152 if ( registry[module] === undefined ) {
1153 mw.loader.register( module );
1154 }
1155 // Check for duplicate implementation
1156 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1157 throw new Error( 'module already implemented: ' + module );
1158 }
1159 // Mark module as loaded
1160 registry[module].state = 'loaded';
1161 // Attach components
1162 registry[module].script = script;
1163 registry[module].style = style;
1164 registry[module].messages = msgs;
1165 // Execute or queue callback
1166 if ( compare(
1167 filter( ['ready'], registry[module].dependencies ),
1168 registry[module].dependencies ) )
1169 {
1170 execute( module );
1171 }
1172 },
1173
1174 /**
1175 * Executes a function as soon as one or more required modules are ready
1176 *
1177 * @param dependencies {String|Array} Module name or array of modules names the callback
1178 * dependends on to be ready before executing
1179 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1180 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1181 */
1182 using: function ( dependencies, ready, error ) {
1183 var tod = typeof dependencies;
1184 // Validate input
1185 if ( tod !== 'object' && tod !== 'string' ) {
1186 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1187 }
1188 // Allow calling with a single dependency as a string
1189 if ( tod === 'string' ) {
1190 dependencies = [dependencies];
1191 }
1192 // Resolve entire dependency map
1193 dependencies = resolve( dependencies );
1194 // If all dependencies are met, execute ready immediately
1195 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
1196 if ( $.isFunction( ready ) ) {
1197 ready();
1198 }
1199 }
1200 // If any dependencies have errors execute error immediately
1201 else if ( filter( ['error'], dependencies ).length ) {
1202 if ( $.isFunction( error ) ) {
1203 error( new Error( 'one or more dependencies have state "error"' ),
1204 dependencies );
1205 }
1206 }
1207 // Since some dependencies are not yet ready, queue up a request
1208 else {
1209 request( dependencies, ready, error );
1210 }
1211 },
1212
1213 /**
1214 * Loads an external script or one or more modules for future use
1215 *
1216 * @param modules {mixed} Either the name of a module, array of modules,
1217 * or a URL of an external script or style
1218 * @param type {String} mime-type to use if calling with a URL of an
1219 * external script or style; acceptable values are "text/css" and
1220 * "text/javascript"; if no type is provided, text/javascript is assumed.
1221 * @param async {Boolean} (optional) If true, load modules asynchronously
1222 * even if document ready has not yet occurred. If false (default),
1223 * block before document ready and load async after. If not set, true will
1224 * be assumed if loading a URL, and false will be assumed otherwise.
1225 */
1226 load: function ( modules, type, async ) {
1227 var filtered, m;
1228
1229 // Validate input
1230 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1231 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1232 }
1233 // Allow calling with an external url or single dependency as a string
1234 if ( typeof modules === 'string' ) {
1235 // Support adding arbitrary external scripts
1236 if ( /^(https?:)?\/\//.test( modules ) ) {
1237 if ( async === undefined ) {
1238 // Assume async for bug 34542
1239 async = true;
1240 }
1241 if ( type === 'text/css' ) {
1242 $( 'head' ).append( $( '<link>', {
1243 rel: 'stylesheet',
1244 type: 'text/css',
1245 href: modules
1246 } ) );
1247 return;
1248 }
1249 if ( type === 'text/javascript' || type === undefined ) {
1250 addScript( modules, null, async );
1251 return;
1252 }
1253 // Unknown type
1254 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1255 }
1256 // Called with single module
1257 modules = [modules];
1258 }
1259
1260 // Filter out undefined modules, otherwise resolve() will throw
1261 // an exception for trying to load an undefined module.
1262 // Undefined modules are acceptable here in load(), because load() takes
1263 // an array of unrelated modules, whereas the modules passed to
1264 // using() are related and must all be loaded.
1265 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1266 if ( registry[modules[m]] !== undefined ) {
1267 filtered[filtered.length] = modules[m];
1268 }
1269 }
1270
1271 // Resolve entire dependency map
1272 filtered = resolve( filtered );
1273 // If all modules are ready, nothing dependency be done
1274 if ( compare( filter( ['ready'], filtered ), filtered ) ) {
1275 return;
1276 }
1277 // If any modules have errors
1278 if ( filter( ['error'], filtered ).length ) {
1279 return;
1280 }
1281 // Since some modules are not yet ready, queue up a request
1282 request( filtered, null, null, async );
1283 return;
1284 },
1285
1286 /**
1287 * Changes the state of a module
1288 *
1289 * @param module {String|Object} module name or object of module name/state pairs
1290 * @param state {String} state name
1291 */
1292 state: function ( module, state ) {
1293 var m;
1294 if ( typeof module === 'object' ) {
1295 for ( m in module ) {
1296 mw.loader.state( m, module[m] );
1297 }
1298 return;
1299 }
1300 if ( registry[module] === undefined ) {
1301 mw.loader.register( module );
1302 }
1303 registry[module].state = state;
1304 },
1305
1306 /**
1307 * Gets the version of a module
1308 *
1309 * @param module string name of module to get version for
1310 */
1311 getVersion: function ( module ) {
1312 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1313 return formatVersionNumber( registry[module].version );
1314 }
1315 return null;
1316 },
1317
1318 /**
1319 * @deprecated since 1.18 use mw.loader.getVersion() instead
1320 */
1321 version: function () {
1322 return mw.loader.getVersion.apply( mw.loader, arguments );
1323 },
1324
1325 /**
1326 * Gets the state of a module
1327 *
1328 * @param module string name of module to get state for
1329 */
1330 getState: function ( module ) {
1331 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1332 return registry[module].state;
1333 }
1334 return null;
1335 },
1336
1337 /**
1338 * Get names of all registered modules.
1339 *
1340 * @return {Array}
1341 */
1342 getModuleNames: function () {
1343 return $.map( registry, function ( i, key ) {
1344 return key;
1345 } );
1346 },
1347
1348 /**
1349 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1350 */
1351 go: function () {
1352 mw.loader.load( 'mediawiki.user' );
1353 }
1354 };
1355 }() ),
1356
1357 /** HTML construction helper functions */
1358 html: ( function () {
1359 function escapeCallback( s ) {
1360 switch ( s ) {
1361 case "'":
1362 return '&#039;';
1363 case '"':
1364 return '&quot;';
1365 case '<':
1366 return '&lt;';
1367 case '>':
1368 return '&gt;';
1369 case '&':
1370 return '&amp;';
1371 }
1372 }
1373
1374 return {
1375 /**
1376 * Escape a string for HTML. Converts special characters to HTML entities.
1377 * @param s The string to escape
1378 */
1379 escape: function ( s ) {
1380 return s.replace( /['"<>&]/g, escapeCallback );
1381 },
1382
1383 /**
1384 * Wrapper object for raw HTML passed to mw.html.element().
1385 * @constructor
1386 */
1387 Raw: function ( value ) {
1388 this.value = value;
1389 },
1390
1391 /**
1392 * Wrapper object for CDATA element contents passed to mw.html.element()
1393 * @constructor
1394 */
1395 Cdata: function ( value ) {
1396 this.value = value;
1397 },
1398
1399 /**
1400 * Create an HTML element string, with safe escaping.
1401 *
1402 * @param name The tag name.
1403 * @param attrs An object with members mapping element names to values
1404 * @param contents The contents of the element. May be either:
1405 * - string: The string is escaped.
1406 * - null or undefined: The short closing form is used, e.g. <br/>.
1407 * - this.Raw: The value attribute is included without escaping.
1408 * - this.Cdata: The value attribute is included, and an exception is
1409 * thrown if it contains an illegal ETAGO delimiter.
1410 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1411 *
1412 * Example:
1413 * var h = mw.html;
1414 * return h.element( 'div', {},
1415 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1416 * Returns <div><img src="&lt;"/></div>
1417 */
1418 element: function ( name, attrs, contents ) {
1419 var v, attrName, s = '<' + name;
1420
1421 for ( attrName in attrs ) {
1422 v = attrs[attrName];
1423 // Convert name=true, to name=name
1424 if ( v === true ) {
1425 v = attrName;
1426 // Skip name=false
1427 } else if ( v === false ) {
1428 continue;
1429 }
1430 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1431 }
1432 if ( contents === undefined || contents === null ) {
1433 // Self close tag
1434 s += '/>';
1435 return s;
1436 }
1437 // Regular open tag
1438 s += '>';
1439 switch ( typeof contents ) {
1440 case 'string':
1441 // Escaped
1442 s += this.escape( contents );
1443 break;
1444 case 'number':
1445 case 'boolean':
1446 // Convert to string
1447 s += String( contents );
1448 break;
1449 default:
1450 if ( contents instanceof this.Raw ) {
1451 // Raw HTML inclusion
1452 s += contents.value;
1453 } else if ( contents instanceof this.Cdata ) {
1454 // CDATA
1455 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1456 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1457 }
1458 s += contents.value;
1459 } else {
1460 throw new Error( 'mw.html.element: Invalid type of contents' );
1461 }
1462 }
1463 s += '</' + name + '>';
1464 return s;
1465 }
1466 };
1467 }() ),
1468
1469 // Skeleton user object. mediawiki.user.js extends this
1470 user: {
1471 options: new Map(),
1472 tokens: new Map()
1473 }
1474 };
1475
1476 }( jQuery ) );
1477
1478 // Alias $j to jQuery for backwards compatibility
1479 window.$j = jQuery;
1480
1481 // Attach to window and globally alias
1482 window.mw = window.mediaWiki = mw;
1483
1484 // Auto-register from pre-loaded startup scripts
1485 if ( jQuery.isFunction( window.startUp ) ) {
1486 window.startUp();
1487 window.startUp = undefined;
1488 }