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